首页 > 解决方案 > 根据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

关于我做错了什么的任何提示?

先感谢您

标签: r

解决方案


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)

推荐阅读