使用dplyr计数

nor*_*ega 2 r dplyr

使用此数据框:

df = data.frame(mes = c(1,1,2,2,3,3), 
                ano = c(1981, 1982,1983), 
                x1 = c(95,8,10,NA,NA,98), 
                x2 = c(NA, NA, 89, 48, NA, 10))
> df
  mes  ano x1 x2
1   1 1981 95 NA
2   1 1982  8 NA
3   2 1983 10 89
4   2 1981 NA 48
5   3 1982 NA NA
6   3 1983 98 10
Run Code Online (Sandbox Code Playgroud)

我想得到这个:

  mes x1_n x2_n
1   1    2    0
2   2    1    2
3   3    1    1
Run Code Online (Sandbox Code Playgroud)

我的意思是,对于每个mes唯一值,我想知道NA有多少非值.我试图与之合作,dplyr::count()但我明白了:

> count(df,mes)
# A tibble: 3 × 2
    mes     n
  <dbl> <int>
1     1     2
2     2     2
3     3     2
Run Code Online (Sandbox Code Playgroud)

有什么想法吗?谢谢.

sin*_*eso 6

count为您提供观察次数.如果您对非NA的观测数量感兴趣,您可以这样做:

 df %>%
   group_by(mes) %>%
   summarize(x1_n = sum(!is.na(x1)),
             x2_n = sum(!is.na(x2)))
Run Code Online (Sandbox Code Playgroud)

  • 为了简化多个`summarize`语句,你可以做`summarize_at(vars(x1,x2),function(x)sum(!is.na(x)))` (3认同)
  • `df%>%group_by(mes)%>%summarise_all(function(x)sum(!is.na(x)))` (2认同)