【问题标题】:Combining Rows Using Observation as Condition使用观察作为条件组合行
【发布时间】:2019-10-08 17:51:46
【问题描述】:

目前正在对我认为存在于 tidyverse 中的 mpg 数据集进行一些分析。我正在尝试获取大型数据集,并将行组合成下面较小的行。

我已经尝试总结将like model和years结合起来得到下面的小表,但无法弄清楚如何在cty为平均值的情况下顺利地做到这一点。

library(tidyverse)

mpg %>%
    group_by(manufacturer, model, year, cty) %>%
    select(manufacturer, model, year, cty) %>%
    summarise(n_model = n()) %>%
    print(n = 15)
# Output
# A tibble: 172 x 5
# Groups:   manufacturer, model, year [76]
   manufacturer model       year   cty n_model
   <chr>        <chr>      <int> <int>   <int>
 1 audi         a4          1999    16       1
 2 audi         a4          1999    18       2
 3 audi         a4          1999    21       1
 4 audi         a4          2008    18       1
 5 audi         a4          2008    20       1
 6 audi         a4          2008    21       1
 7 audi         a4 quattro  1999    15       1
 8 audi         a4 quattro  1999    16       1
 9 audi         a4 quattro  1999    17       1
10 audi         a4 quattro  1999    18       1
11 audi         a4 quattro  2008    15       1
12 audi         a4 quattro  2008    17       1
13 audi         a4 quattro  2008    19       1
14 audi         a4 quattro  2008    20       1
15 audi         a6 quattro  1999    15       1
# … with 157 more rows
# Looking for this
manufacturer model year     avg_cty     n
audi          a4    1999    18.25000    4
audi          a4    2008    19.66667    3

预期的是较小的表格,它结合了模型和年份,以及平均城市汽油里程(和计数)。任何帮助表示赞赏!

【问题讨论】:

  • 你应该根据什么分组
  • 分组应该是制造商,型号,年份,avg_cty(需要定义),然后是计数(n)。由于类似年份有多个 cty,我希望压缩这些行。
  • 我的意思是压缩数据分组应该是什么

标签: r group-by summarize


【解决方案1】:

使用data.table

library(data.table)
setDT(mpg)[, .(city = mean(cty), n_model = .N), .(manufacturer, model, year)]

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 2015-08-02
    • 1970-01-01
    • 2014-03-23
    • 2018-06-04
    • 1970-01-01
    • 2021-08-26
    • 1970-01-01
    相关资源
    最近更新 更多