无效因子级别,NA生成R

时间:2014-04-29 04:57:18

标签: string r replace numeric

我正在使用的数据样本如下。我已经使用" NA"省略了所有行。在他们中。

gss.s[1:5,]
      abany          advfront   arrest
2      YES             Agree       NO
3      YES    Strongly agree       YES
10     YES             Agree       YES
16     YES             Agree       NO
21      NO    Strongly agree       NO

我正在尝试更换" YES"在abany列中有1和" NO"在abany列中为-1。我尝试使用替换替换(gss.s [,1]," YES",1),但得到错误无效因子级别,NA生成。我读了一篇关于同样问题的上一篇文章,但无法弄清楚如何将解决方案应用到我的问题中。

3 个答案:

答案 0 :(得分:2)

您可以在列上使用ifelse(),一次更改所有值。

gss.s$abany <- ifelse(gss.s$abany == "YES", 1, -1)
gss.s
##    abany       advfront arrest
## 2      1          Agree     NO
## 3      1 Strongly agree    YES
## 10     1          Agree    YES
## 16     1          Agree     NO
## 21    -1 Strongly agree     NO

答案 1 :(得分:2)

y <- data.frame ("abany"=c("YES","YES","YES","YES","NO"), 
            "advfront"=c("Agree","Strongly Agree","Agree","Agree","Strongly Agree"),
            "arrest"=c("NO","YES","YES","NO","NO"))

我会尝试另一种方式: 将因子列转换为字符

y$abany <- as.character.factor (y$abany)

所以现在你没有任何问题来改变列的值

y[y$abany=="YES", "abany"] <- 1
y[y$abany=="NO", "abany"] <- -1

答案 2 :(得分:0)

您还可以创建一个向量,在其中定义要进行的更改。如果您将大数据集与ifelse语句进行比较,则会快得多。

translate <- c(YES=1,NO=-1)
gss.s$abany2 <- translate[as.character(gss.s$abany)] 
gss.s

#   abany       advfront arrest abany2
# 1   YES          Agree     NO      1
# 2   YES Strongly agree    YES      1
# 3   YES          Agree    YES      1
# 4   YES          Agree     NO      1
# 5    NO Strongly agree     NO     -1

如果要进行多项更改,您也不必为嵌套的ifelse函数而烦恼:

translate2 <- c('Strongly agree'=2,Agree=1,Disagree=-1,'Strongly disagree'=-2 )
gss.s$advfront2 <- translate2[as.character(gss.s$advfront)]
gss.s

#   abany       advfront arrest abany2 advfront2
# 1   YES          Agree     NO      1         1
# 2   YES Strongly agree    YES      1         2
# 3   YES          Agree    YES      1         1
# 4   YES          Agree     NO      1         1
# 5    NO Strongly agree     NO     -1         2