如何将变量的两个字符值转换为数字值?

问题描述 投票:0回答:1

我有一个名为“ess”的数据集。 有一个名为 ess$trstprl 的变量。 它的类别是一个因素,它的值是“完全不信任”、1:9、“完全信任”。 我需要做的是转换“完全不信任”和“完全信任”变量,以便它们显示“0”和“10”,而不是文本。

到目前为止我所有的尝试都失败了。任何意见,将不胜感激!另外,如果可能的话,因为这是一项家庭作业,所以我需要避免使用 dplyr,所以如果可能的话,只需在基础 R 中进行即可。

table(ess$trstprl)
class(ess$trstprl)

ess$trstprl_binarni=ess$trstprl
for (i in ess$trstprl) {
  if (ess$trstprl=="No trust at all") {
    ess$trstprl[ess$trstprl,]=0
  }
}

这失败了,因为条件显然长度>1。

r
1个回答
0
投票
trstprl <- sample(c("No trust at all",1:9,"Complete trust"), 100, T)
trstprl <- factor(trstprl, ordered = F)
unique(trstprl) # will list "No trust at all" and "Complete trust"
install.packages("plyr")
trstprl <- plyr::mapvalues(trstprl, c("No trust at all", "Complete trust"), c("0","10"))
unique(trstprl) # will NOT list "No trust at all" and "Complete trust"
© www.soinside.com 2019 - 2024. All rights reserved.