首页 > 解决方案 > 如何创建一个新列来指示某些其他列是否包含给定值?

问题描述

我想要 data.frame 中的一个新列来指示对于每一行,数字“2”是否出现在某些其他列中。这是一个适用于小型 data.frame 的简单版本:

df <- data.frame(mycol.1 = 1:5,  mycol.2= 5:1, other.col = -2:2)
df$mycols.contain.two <- df$mycol.1 ==2 | df$mycol.2 ==2
df

  mycol.1 mycol.2 other.col mycols.contain.two
1       1       5        -2              FALSE
2       2       4        -1               TRUE
3       3       3         0              FALSE
4       4       2         1               TRUE
5       5       1         2              FALSE

现在假设 data.frame 有 50 列,我希望新列指示是否有任何以“mycol”开头的列在每行中包含“2”,而不必使用“|” 符号 49 次。我假设使用 dplyr 有一个优雅的答案starts_with(),但我无法弄清楚语法。

标签: rdplyr

解决方案


你可以这样做:

df <- data.frame(mycol.1 = 1:5,  mycol.2= 5:1, other.col = -2:2)
df$TYPE <- ifelse(rowSums(ifelse(sapply(df, function (x){x == 2}), 1, 0)) > 0 , "TRUE", "FALSE")

# > df
# mycol.1 mycol.2 other.col  TYPE
# 1       1       5        -2 FALSE
# 2       2       4        -1  TRUE
# 3       3       3         0 FALSE
# 4       4       2         1  TRUE
# 5       5       1         2  TRUE

推荐阅读