英文:
Turn a Character Vector into Numeric Vector with labels
问题
这似乎非常基本,但我找不到高效的方法来做到这一点:
我有字符向量
s<-c("LabelB","LabelX", "LabelE", "LabelE", "LabelX", "LabelD", "LabelB")
我想要的是一个可以按顺序解释数字的数字向量
library(haven)
library(labelled)
labelledS<-c(1,4,3,3,4,2,1)
带有标签,即保留标签
Labels
value label
1 LabelB
2 LabelD
3 LabelE
4 LabelX
我可以使用除了 haven 或 labelled 之外的其他包。因为我有许多级别和标签,我只想确保这样做时不手动重新编码变量。
我尝试了一些方法:
names(MyLevels) <- levels(as.factor(s))
labelledS <- labelled(s, as.factor(MyLevels))```
然而,在这里,变量的值仍然是字符串,而我希望它们是整数。
非常感谢您的帮助!
<details>
<summary>英文:</summary>
This seems extremely basic but I cannot find an efficient way to do this:
I have character vector
```s<-c("LabelB","LabelX", "LabelE", "LabelE", "LabelX", "LabelD", "LabelB")```
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)
with labels, i.e. the labels are preserved with
Labels
value label
1 LabelB
2 LabelD
3 LabelE
4 LabelX
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.
I tried things like:
MyLevels <- c(1,2,3,4)
names(MyLevels) <- levels(as.factor(s))
labelledS <- labelled(s, as.factor(MyLevels))
However, here the values of the variables remain strings, whereas I want them to be integers.
Thank you very much for your help!
</details>
# 答案1
**得分**: 1
这是用 `haven` 正确执行的方法:
```R
v1 <- as.integer(factor(s))
levels = levels(factor_s)
values = seq_along(levels)
res <- haven::labelled(v1, setNames(object = values, nm = levels))
res
<labelled<integer>[7]>
[1] 1 4 3 3 4 2 1
Labels:
value label
1 LabelB
2 LabelD
3 LabelE
4 LabelX
英文:
Here is the correct way to do it with haven
,
v1 <- as.integer(factor(s))
levels = levels(factor_s)
values = seq_along(levels)
res <- haven::labelled(v1, setNames(object = values, nm = levels))
res
<labelled<integer>[7]>
[1] 1 4 3 3 4 2 1
Labels:
value label
1 LabelB
2 LabelD
3 LabelE
4 LabelX
通过集体智慧和协作来改善编程学习和解决问题的方式。致力于成为全球开发者共同参与的知识库,让每个人都能够通过互相帮助和分享经验来进步。
评论