R For Loop Not Working

时间:2014-06-05 20:02:45

标签: r for-loop

Mydata设置测试如下。我想创建一个新变量“indicator”,如果所有变量都等于1(例如第3行),则为= 1。

   id    X10J X10f X10m X10ap  X10myy X10junn X10julyy
 1  1001    2    2    2     2      2       2        2
 2  1002    1    1   -1     2      1       1        1
 3  1003    1    1    1     1      1       1        1
 4  1004    1    1    2     1      1       1        1
 12 1012    1    2    1     1      1       1        1

我创建了以下for循环:

for (i in c(test$X10J,test$X20f,test$X10m,test$X10ap,test$Xmyy,test$X10junn,test$X10julyy)){
    if(i==1){
            test$indicator=1
    }else if(i==2|i==-1){
            test$indicator=0  
    }
}

这会创建一个变量,其中所有值= 1而不是0和-1。

3 个答案:

答案 0 :(得分:3)

矢量化解决方案:

test$indicator <- ifelse(rowSums(test[,-1] ==1)==ncol(test[,-1]),1,0)

答案 1 :(得分:1)

无需for循环。您可以使用apply

> test$indicator <- apply(test[-1], 1, function(x) ifelse(all(x == 1), 1, 0))
> test
     id X10J X10f X10m X10ap X10myy X10junn X10julyy indicator
1  1001    2    2    2     2      2       2        2         0
2  1002    1    1   -1     2      1       1        1         0
3  1003    1    1    1     1      1       1        1         1
4  1004    1    1    2     1      1       1        1         0
12 1012    1    2    1     1      1       1        1         0

答案 2 :(得分:0)

你可以使用:

indicator <- apply(test[,-1], 1, function(row)
                   {
                   ifelse(all(row==1), 1, 0)
                   })

注意:apply的第二个参数是1,如果你有行,2是列。

相关问题