我知道这是一个重复的问题,但我似乎无法再次找到该帖子
使用以下数据
df <- data.frame(A=c(1,1,2,2),B=c(NA,2,NA,4),C=c(3,NA,NA,5),D=c(NA,2,3,NA),E=c(5,NA,NA,4))
A B C D E
1 NA 3 NA 5
1 2 NA 2 NA
2 NA NA 3 NA
2 4 5 NA 4
按 A
分组,我希望使用 tidyverse
解决方案获得以下输出
A B C D E
1 2 3 2 5
2 4 5 3 4
我在 A
中有很多组。我想我看到了使用coalesce
的答案,但我不确定如何让它工作。我想要一个也适用于字符
的解决方案。谢谢!
最佳答案
我还没有弄清楚如何将 coalesce_by_column
函数放入 dplyr
管道中,但这可行:
coalesce_by_column <- function(df) {
return(coalesce(df[1], df[2]))
}
df %>%
group_by(A) %>%
summarise_all(coalesce_by_column)
## A B C D E
## <dbl> <dbl> <dbl> <dbl> <dbl>
## 1 1 2 3 2 5
## 2 2 4 5 3 4
<小时/>
编辑:包括@Jon Harmon 针对超过 2 名群组成员的解决方案
# Supply lists by splicing them into dots:
coalesce_by_column <- function(df) {
return(dplyr::coalesce(!!! as.list(df)))
}
df %>%
group_by(A) %>%
summarise_all(coalesce_by_column)
#> # A tibble: 2 x 5
#> A B C D E
#> <dbl> <dbl> <dbl> <dbl> <dbl>
#> 1 1 2 3 2 5
#> 2 2 4 5 3 4
关于r - 组合数据框中包含 NA 的行以形成完整的行,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/45515218/