dplyr按组计算非NA值 [英] dplyr count non-NA value in group by
本文介绍了dplyr按组计算非NA值的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
这是我的例子
mydf<-data.frame('col_1'=c('A','A','B','B'), 'col_2'=c(100,NA, 90,30))
我想按 col_1
进行分组,并在 col_2
I would like to group by col_1
and count not-NA elements in col_2
我想用 dplyr
来做到这一点。
我在搜索SO后搜索的内容:
Here is what I tried after searching SO:
mydf %>% group_by(col_1) %>% summarise_each(funs(!is.na(col_2)))
mydf %>% group_by(col_1) %>% mutate(non_na_count = length(col_2, na.rm=TRUE))
mydf %>% group_by(col_1) %>% mutate(non_na_count = count(col_2, na.rm=TRUE))
没有工作。任何建议?
推荐答案
您可以使用这个
You can use this
mydf %>% group_by(col_1) %>% summarise(non_na_count = sum(!is.na(col_2)))
# A tibble: 2 x 2
col_1 non_na_count
<fctr> <int>
1 A 1
2 B 2
这篇关于dplyr按组计算非NA值的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!
查看全文