r - 如何创建一个新列来指示某些其他列是否包含给定值?
问题描述
我想要 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()
,但我无法弄清楚语法。
解决方案
你可以这样做:
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
推荐阅读
- netlogo - 如何改变特定区域总数中 n 只海龟的颜色?
- javascript - 选择时,v-calendar 不会突出显示道具内的日期
- html - 对 h1 标题的更改会影响整个页面,但会更改目标元素
- java - Vaadin addSucceededListener
- async-await - NextJs - 节点 - API 已解析,但未发送 /api/xxx 响应
- azure - 将数据从 SnowFlake 卸载到 ADLS
- python - 无法找出舍入函数中的(可能的)最后一个错误(Python)
- c++ - 如何将用户指定的编译时整数常量添加到可变参数类模板?
- discord - 命令已弃用
- json - Swift JSON 解码网址