【问题标题】:Coalesce two columns with a condition in dplyr在 dplyr 中使用条件合并两列
【发布时间】:2021-02-23 01:47:31
【问题描述】:

我想合并两列以删除所有 NA 但同时两列都有值我想只保留最高值。

例子:

df <- data.frame(A = c(1,0,1,0,1,1,0,0,NA),
                 B = c(0,NA,1,1,NA,1,0,1,1))

   A  B
1  1  0
2  0 NA
3  1  1
4  0  1
5  1 NA
6  1  1
7  0  0
8  0  1
9 NA  1

想要的结果

   A  B C
1  1  0 1
2  0 NA 0
3  1  1 1
4  0  1 1
5  1 NA 1
6  1  1 1
7  0  0 0
8  0  1 1
9 NA  1 1

【问题讨论】:

  • do.call(pmax, c(df, na.rm = TRUE))
  • +!!rowSums(df, na.rm = TRUE) 如果你的列都是 0/1s

标签: r dplyr tidyverse coalesce


【解决方案1】:

您可以计算删除NA 值的行最大值:

matrixStats::rowMaxs(as.matrix(df), na.rm = TRUE)
#[1] 1 0 1 1 1 1 0 1 1

或者dplyr

library(dplyr)

df %>%
  rowwise() %>%
  mutate(C = max(c_across(), na.rm = TRUE))

#     A     B     C
#  <dbl> <dbl> <dbl>
#1     1     0     1
#2     0    NA     0
#3     1     1     1
#4     0     1     1
#5     1    NA     1
#6     1     1     1
#7     0     0     0
#8     0     1     1
#9    NA     1     1

【讨论】:

  • 非常感谢! “c_across”真的有必要吗?它似乎只适用于cross。
  • 是的,这可行,但across 用于按列操作。与rowwise 一起使用时,最好使用c_across,因为它就是为此而设计的。
【解决方案2】:

我们可以使用reducepmax

library(dplyr)
library(purrr)
df %>% 
    mutate(C = reduce(., pmax, na.rm = TRUE))

-输出

#   A  B C
#1  1  0 1
#2  0 NA 0
#3  1  1 1
#4  0  1 1
#5  1 NA 1
#6  1  1 1
#7  0  0 0
#8  0  1 1
#9 NA  1 1

【讨论】:

    猜你喜欢
    • 2023-04-07
    • 2021-11-13
    • 1970-01-01
    • 2023-02-14
    • 1970-01-01
    • 2021-04-19
    • 1970-01-01
    • 2021-03-20
    • 1970-01-01
    相关资源
    最近更新 更多