【问题标题】:R For Loop Not WorkingR For 循环不工作
【发布时间】:2014-06-05 20:02:44
【问题描述】:

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

   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 的变量。

【问题讨论】:

    标签: r for-loop


    【解决方案1】:

    矢量化解决方案:

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

    【讨论】:

      【解决方案2】:

      不需要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
      

      【讨论】:

        【解决方案3】:

        你可以使用:

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

        注意:apply 的第二个参数是 1 代表行,2 代表列。

        【讨论】:

          猜你喜欢
          • 2019-06-13
          • 2011-06-02
          • 2013-12-25
          • 1970-01-01
          • 1970-01-01
          • 2015-02-03
          • 2017-01-19
          • 1970-01-01
          • 1970-01-01
          相关资源
          最近更新 更多