将字符向量转换为带标签的数值向量

huangapple go评论132阅读模式
英文:

Turn a Character Vector into Numeric Vector with labels

问题

这似乎非常基本,但我找不到高效的方法来做到这一点:

我有字符向量

s<-c("LabelB","LabelX", "LabelE", "LabelE", "LabelX", "LabelD", "LabelB")

我想要的是一个可以按顺序解释数字的数字向量

  1. library(haven)
  2. library(labelled)
  3. labelledS<-c(1,4,3,3,4,2,1)

带有标签,即保留标签

  1. Labels
  2. value label
  3. 1 LabelB
  4. 2 LabelD
  5. 3 LabelE
  6. 4 LabelX

我可以使用除了 haven 或 labelled 之外的其他包。因为我有许多级别和标签,我只想确保这样做时不手动重新编码变量。

我尝试了一些方法:

  1. names(MyLevels) <- levels(as.factor(s))
  2. labelledS <- labelled(s, as.factor(MyLevels))```
  3. 然而,在这里,变量的值仍然是字符串,而我希望它们是整数。
  4. 非常感谢您的帮助!
  5. <details>
  6. <summary>英文:</summary>
  7. This seems extremely basic but I cannot find an efficient way to do this:
  8. I have character vector
  9. ```s&lt;-c(&quot;LabelB&quot;,&quot;LabelX&quot;, &quot;LabelE&quot;, &quot;LabelE&quot;, &quot;LabelX&quot;, &quot;LabelD&quot;, &quot;LabelB&quot;)```
  10. What I want is a numeric vector where the numbers can be interpreted ordinally

library(haven)
library(labelled)
labelledS<-c(1,4,3,3,4,2,1)

  1. with labels, i.e. the labels are preserved with

Labels
value label
1 LabelB
2 LabelD
3 LabelE
4 LabelX

  1. I am open to using other packages besides haven or labelled. As I have many levels and labels, I just want to make sure that this is done without manually recoding the variable.
  2. I tried things like:

MyLevels <- c(1,2,3,4)
names(MyLevels) <- levels(as.factor(s))
labelledS <- labelled(s, as.factor(MyLevels))

  1. However, here the values of the variables remain strings, whereas I want them to be integers.
  2. Thank you very much for your help!
  3. </details>
  4. # 答案1
  5. **得分**: 1
  6. 这是用 `haven` 正确执行的方法:
  7. ```R
  8. v1 <- as.integer(factor(s))
  9. levels = levels(factor_s)
  10. values = seq_along(levels)
  11. res <- haven::labelled(v1, setNames(object = values, nm = levels))
  12. res
  13. <labelled<integer>[7]>
  14. [1] 1 4 3 3 4 2 1
  15. Labels:
  16. value label
  17. 1 LabelB
  18. 2 LabelD
  19. 3 LabelE
  20. 4 LabelX
英文:

Here is the correct way to do it with haven,

  1. v1 &lt;- as.integer(factor(s))
  2. levels = levels(factor_s)
  3. values = seq_along(levels)
  4. res &lt;- haven::labelled(v1, setNames(object = values, nm = levels))
  5. res
  6. &lt;labelled&lt;integer&gt;[7]&gt;
  7. [1] 1 4 3 3 4 2 1
  8. Labels:
  9. value label
  10. 1 LabelB
  11. 2 LabelD
  12. 3 LabelE
  13. 4 LabelX

huangapple
  • 本文由 发表于 2023年6月29日 19:48:33
  • 转载请务必保留本文链接:https://go.coder-hub.com/76580755.html
匿名

发表评论

匿名网友

:?: :razz: :sad: :evil: :!: :smile: :oops: :grin: :eek: :shock: :???: :cool: :lol: :mad: :twisted: :roll: :wink: :idea: :arrow: :neutral: :cry: :mrgreen:

确定