根据条件将列名写入变量

时间:2014-11-14 00:09:23

标签: r if-statement apply lapply

我有一堆二进制变量,当变量为1时我想在列名中替换,否则为空。

数据框before如下所示:

Apple Orange Banana
0 1 0
1 1 1
1 0 0
0 0 1

我想谈谈这个问题(after):

Apple Orange Banana
   NA Orange     NA
Apple Orange Banana
Apple     NA     NA
   NA     NA Banana

我尝试过使用各种应用功能而没有运气。例如,我无法弄清楚为什么这段代码不起作用:

after <- apply(before,1,function(x) ifelse(x==1,colnames(x),NA))

4 个答案:

答案 0 :(得分:3)

您也可以尝试

 df[] <- names(df)[(NA^!df)+col(df)-1]
 df
 # Apple Orange Banana
 #1  <NA> Orange   <NA>
 #2 Apple Orange Banana
 #3 Apple   <NA>   <NA>
 #4  <NA>   <NA> Banana

数据

 df <- structure(list(Apple = c(0L, 1L, 1L, 0L), Orange = c(1L, 1L, 
 0L, 0L), Banana = c(0L, 1L, 0L, 1L)), .Names = c("Apple", "Orange", 
 "Banana"), class = "data.frame", row.names = c(NA, -4L))

答案 1 :(得分:2)

通过创建ifelse

的向量,您可以在没有apply循环的情况下使用names
df[] <- ifelse(df == 1L, names(df)[col(df)], NA)

导致

#   Apple Orange Banana
# 1  <NA> Orange   <NA>
# 2 Apple Orange Banana
# 3 Apple   <NA>   <NA>
# 4  <NA>   <NA> Banana

原始df

的位置
structure(list(Apple = c(0L, 1L, 1L, 0L), Orange = c(1L, 1L, 
0L, 0L), Banana = c(0L, 1L, 0L, 1L)), .Names = c("Apple", "Orange", 
"Banana"), class = "data.frame", row.names = c(NA, -4L))

答案 2 :(得分:2)

或者没有使用等级

的人
df[] <- t(apply(df, 1, function(x){ifelse(x==1, names(x), NA)}))
  Apple Orange Banana
1  <NA> Orange   <NA>
2 Apple Orange Banana
3 Apple   <NA>   <NA>
4  <NA>   <NA> Banana

答案 3 :(得分:0)

这个怎么样?

m[m == 1] <- rep(colnames(m), each = 4)[(m == 1)]
m[m == 0] <- NA
m
  Apple Orange Banana
1  <NA> Orange   <NA>
2 Apple Orange Banana
3 Apple   <NA>   <NA>
4  <NA>   <NA> Banana