首页 > 解决方案 > 根据数据框子集中的条件在 R 中添加新列

问题描述

我有以下数据集:

 df <- data.frame("attribute"=c('name', 'age', 'location'),
                "A"=c(1,0,0), "B"=c(0,1,1), "C"=c(1,0,1))
 names(df) <- c("attribute", "A", "B", "C")
 df

    attribute   A B C
        name    1 0 1
        age     0 1 0
     location   0 1 1

我无法解决这个问题。

标签: rloopsdataframe

解决方案


我们可以用max.col

df$Column <- names(df)[-1][max.col(df[-1], 'first')]
df$Column
#[1] "A" "B" "B"

推荐阅读