【问题标题】:R data frame - Include NAs in aggregation [duplicate]R数据框-在聚合中包含NA[重复]
【发布时间】:2017-01-30 16:58:31
【问题描述】:

使用数据框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|
+-----------------------------------------+

在像下面这样的聚合中,我想用NA 保留makes - 如何实现这一点?可以将makeNA 组合在一起。

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

【问题讨论】:

  • aggregate(reg ~ addNA(make), df1, length) 来自副本。对我来说它有效。

标签: r


【解决方案1】:

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

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

【讨论】:

    猜你喜欢
    • 2021-09-17
    • 1970-01-01
    • 1970-01-01
    • 2015-07-04
    • 2020-10-25
    • 1970-01-01
    • 2015-11-19
    • 1970-01-01
    • 2017-08-28
    相关资源
    最近更新 更多