如何按R中两列中的名称聚合?

sfe*_*tan 4 merge aggregate r na

我得到了一个数据帧:

a <- c('A','A','B','B','A')
b <- c(1,1,1,1,2)
c <- c(NA,60,NA,100,NA)
d <- c(10,NA,10,NA,100)

frame <- data.frame(a,b,c,d)

> frame
  a  b   c  d
1 A  1  NA  10
2 A  1  60  NA
3 B  1  NA  10
4 B  1 100  NA
5 A  2  NA  100
Run Code Online (Sandbox Code Playgroud)

我想通过 a 和 b 聚合它

>frame2
  a  b   c  d
1 A  1  60  10
3 B  1 100  10
5 A  2  NA  100
Run Code Online (Sandbox Code Playgroud)

我尝试了几种方法,例如来自 dplyr 的 agregat() 和 group,但不知何故它永远不起作用。我猜NA是一个问题。

akr*_*run 6

有了aggregate,我们可能需要使用na.action

aggregate(.~ a + b, frame, sum, na.rm = TRUE, na.action = 'na.pass')
#   a b   c   d
#1 A 1  60  10
#2 B 1 100  10
#3 A 2   0 100
Run Code Online (Sandbox Code Playgroud)

如果我们打算对行进行子集

library(dplyr)
frame %>% 
    group_by(a, b) %>%
    mutate_at(vars(-group_cols()), ~ .[order(is.na(.))]) %>% 
    slice(1)
# A tibble: 3 x 4
# Groups:   a, b [3]
#  a         b     c     d
#  <fct> <dbl> <dbl> <dbl>
#1 A         1    60    10
#2 A         2    NA   100
#3 B         1   100    10
Run Code Online (Sandbox Code Playgroud)