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

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

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&lt;-c(&quot;LabelB&quot;,&quot;LabelX&quot;, &quot;LabelE&quot;, &quot;LabelE&quot;, &quot;LabelX&quot;, &quot;LabelD&quot;, &quot;LabelB&quot;)```
 

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 &lt;- as.integer(factor(s))
levels = levels(factor_s)
values = seq_along(levels)

res &lt;- haven::labelled(v1, setNames(object = values, nm = levels))

res
&lt;labelled&lt;integer&gt;[7]&gt;
[1] 1 4 3 3 4 2 1

Labels:
 value  label
     1 LabelB
     2 LabelD
     3 LabelE
     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:

确定