将多个条件应用于数据框的不同列

时间:2012-12-18 11:48:27

标签: r

我有以下数据框:

id1 id2 qtty    cat output
15994   15994   30  1   1
25787   26275   7   2   1
122301  122301  0   0   0
36199   35333   14  2   1
36199   36199   15  1   1
46223   45746   14  2   1
46223   46223   15  1   1
80570   80570   0   0   0
55728   55728   1   1   1
94218   94218   0   0   0
69456   66837   5   2   1

其中cat是我想根据以下标准生成的列:

id1=id2 and qtty=0 then cat=0
id1=id2 and qtty>0 then cat=1
id1!=id2 and qtty=0 then cat=2
id1!=id2 and qtty>0 then cat=2

output是我得到的,我做的是:

  status<-function(dataframe){
  store<-rep(0,length(dataframe[,1]))
  for(i in 1: length(dataframe[,1])) {
    if(dataframe[i,1]==dataframe[i,2]) {
      if(dataframe[i,3]==0) {store[i]<-0}
        else
          if(dataframe[i,1]==dataframe[i,2]) {
            if(dataframe[i,3]>0) {store[i]<-1}
              else
                if(dataframe[i,1]!=dataframe[i,2]) {
                  if(dataframe[i,3]>0) {store[i]<-2}
                    else store[i]<-2
               }
            }
         }
     }
  return(store)
}

任何帮助将不胜感激。

1 个答案:

答案 0 :(得分:5)

可以使用ifelse完成此操作:(假设dat是您的数据框)

within(dat, cat <- ifelse(id1 != id2, 2, qtty > 0))

结果:

      id1    id2 qtty cat output
1   15994  15994   30   1      1
2   25787  26275    7   2      1
3  122301 122301    0   0      0
4   36199  35333   14   2      1
5   36199  36199   15   1      1
6   46223  45746   14   2      1
7   46223  46223   15   1      1
8   80570  80570    0   0      0
9   55728  55728    1   1      1
10  94218  94218    0   0      0
11  69456  66837    5   2      1

工作原理:

函数ifelse检查id1id2是否相同。如果是这种情况,则会将值2分配给cat中的相应条目。如果它们不相同,则分配qtty > 0的结果。后者返回布尔值(FALSETRUE)的逻辑向量,这些值被转换为整数(01)。

相关问题