r - 根据R中的条件合并数据框中的多列
问题描述
我对 R 很陌生,我想做以下事情:
我有一个由ID, Col1, Col2, Col3
列组成的数据框。
df <- read.table(header = TRUE, stringsAsFactors = FALSE, text="
ID Col1 Col2 Col3
1 0 'Less than once a month' 0
2 Never 0 0
3 0 0 'Once a month'
")
我想将这 3 列合并为一列,如果有"Never"
,0
其他列中的值为"Never"
,如果有"Once a month"
,其余的是0
,然后"Once a month"
依此类推。所有列都是互斥的,这意味着不能在"Never"
同"Once a month"
一个 raw 中。
//I tried to apply this loop:
for (val in df) {
if(df$Col1 == "Never" && df$Col2 == "0")
{
df$consolidated <- "Never"
} else (df$`Col1 == "0" && df$Col2 == "Less than once a month")
{
how_oft_purch_gr_pers$consolidated <- "Less than once a month"
}
}
我只想先计算两列,但它没有用,因为合并列中的所有原始数据都填充了“每月少于一次”。
我希望它是这样的:
ID Col1 Col2 Col3 Consolidated
1 0 Less than once a month 0 Less than once a month
2 Never 0 0 Never
3 0 0 Once a month Once a month
关于我做错了什么的任何提示?
先感谢您
解决方案
dplyr::coalesce
替换0
为 NA后可以考虑使用。查找第coalesce()
一个非缺失值(在本例中为一行)并创建一个新列。解决方案可以是:
library(dplyr)
df %>% mutate_at(vars(starts_with("Col")), funs(na_if(.,"0"))) %>%
mutate(Consolidated = coalesce(Col1,Col2,Col3)) %>%
select(ID, Consolidated)
# OR in concise way once can simply write as
bind_cols(df[1], Consolidated = coalesce(!!!na_if(df[-1],"0")))
# ID Consolidated
# 1 1 Less than once a month
# 2 2 Never
# 3 3 Once a month
数据:
df <- read.table(text =
"ID Col1 Col2 Col3
1 0 'Less than once a month' 0
2 Never 0 0
3 0 0 'Once a month'",
stringsAsFactors = FALSE, header = TRUE)
推荐阅读
- ios - AVAudioEngine - 更改 inputNode 的音频单元设备后输出格式有 0 个通道
- matlab - 如何检查系统是否有 `Simulink Coder 的许可证?
- javascript - 如何在 React 中管理组件状态(加载、错误、数据)
- vips - 带有白色背景的 libvips 中的范围图像
- omnet++ - 一个关于omnet++无线节点源码的问题
- python - 删除没有生命周期规则的旧 s3 对象
- fastapi - Fastapi auth with OAuth2PasswordBearer,如何检查用户是否已连接而不引发异常?
- azure-devops - Azure Dev Ops 登录以访问单个项目
- python - 扩展字典数据框列表
- c# - 如何让 Agora RTM 在 C# web 应用中运行?