R数据帧 - 在聚合中包含NA

时间:2017-01-30 07:35:28

标签: r

使用如下所示的数据框df1

+-----------------------------------------+
|reg   |make  |model  |year|abs  |gears|fm|
+-----------------------------------------+
|ax1234|Toyota|Corolla|1999|true |6    |0 |
|ax1235|Toyota|Corolla|1999|false|5    |0 |
|ax1236|Toyota|Corolla|1992|false|4    |NA|
|ax1237|Toyota|Camry  |2001|true |7    |1 |
|ax1238|Honda |Civic  |1994|true |5    |NA|
|ax1239|Honda |Civic  |2000|false|6    |0 |
|ax1240|Honda |Accord |1992|false|4    |NA|
|ax1241|Nissan|Sunny  |2001|true |6    |0 |
|ax1242|      |       |1998|false|6    |0 |
|ax1243|NA    |NA     |1992|false|4    |NA|
+-----------------------------------------+

如下所示汇总,我想用make保留NA - 如何实现这一目标?将makeNA组合在一起很好。

> aggregate(reg ~ make, df1, length)
    make reg
1          1
2  Honda   3
3 Nissan   1
4 Toyota   4

1 个答案:

答案 0 :(得分:2)

我们可以使用dplyr,它也会提供NA计数

library(dplyr)
 df1 %>% 
    group_by(make) %>%
    summarise(reg = n())