选择具有正值的列

时间:2014-05-28 14:01:12

标签: r

我正在处理一个数据帧,我正在尝试使用R来计算包含数据的列名。我有一个下面列出的示例数据框:

df <-structure(
  list(
    area = structure(1:9, 
      .Label = c("a", "b", "c", "d", "e", "f", "g", "h", "i"), 
       class = "factor"
    ), 
    cat = c(5L, 0L, 0L, 0L, 0L, 0L, 0L, 3L, 0L), 
    dog = c(0L, 10L, 0L, 0L, 0L, 0L, 0L, 0L, 11L), 
    rabbit = c(0L, 0L, 0L, 3L, 0L, 0L, 0L, 0L, 0L), 
    horse = c(0L, 0L, 8L, 0L, 0L, 0L, 0L, 0L, 0L), 
    sheep = c(0L, 0L, 0L, 0L, 9L, 0L, 0L, 0L, 0L), 
    mouse = c(0L, 0L, 0L, 0L, 0L, 5L, 0L, 0L, 0L), 
    rat = c(0L, 0L, 0L, 0L, 0L, 0L, 2L, 0L, 0L)
  ), 
  .Names = c("area", "cat", "dog", "rabbit", "horse", "sheep", "mouse", "rat"), 
  class = "data.frame", 
  row.names = c(NA, -9L)
)

来自&#39; cat&#39;的列去老鼠&#39;只有一列(其余为零)有正值。如何让R添加一个名为&#39; animal&#39;给我每个区域的动物名称(从列名称)有正值,即列动物&#39;会读猫,狗,马,兔,羊等吗?

任何寻求帮助或指导的地方都会感激不尽。

非常感谢提前。

1 个答案:

答案 0 :(得分:1)

df$animal <- names(df)[-1][apply( df[,-1] , 1, which.max )]
df
#  area cat dog rabbit horse sheep mouse rat animal
#1    a   5   0      0     0     0     0   0    cat
#2    b   0  10      0     0     0     0   0    dog
#3    c   0   0      0     8     0     0   0  horse
#4    d   0   0      3     0     0     0   0 rabbit
#5    e   0   0      0     0     9     0   0  sheep
#6    f   0   0      0     0     0     5   0    pos
#7    g   0   0      0     0     0     0   2    pos
#8    h   3   0      0     0     0     0   0    cat
#9    i   0  11      0     0     0     0   0    dog