【问题标题】:Aggregate data in one column based on values/factors in four another columns根据另外四列中的值/因素聚合一列中的数据
【发布时间】:2016-06-09 13:36:51
【问题描述】:

我的 R 脚本中有一个数据框,看起来像这样:

> head(species.prop)
Source: local data frame [6 x 5]

   year month  area species catch.p
  (dbl) (dbl) (chr)   (chr)   (dbl)
1  1998     4  VI      hom    17.25
2  1998     5  VII     pil    17.25
3  2000     4  VI      hom    40.25
4  1998     4  IV      hom    27.60
5  2000     1  VII     pil    46.00
6  1998     4  VI      pil     8.05

我想做的是改变数据框,这样它就会给我每年每个月每个区域每个物种的 catch.p 总和。结果应该是一个像上面一样的数据框,具有所有相同的列标题。

我试过聚合:

> aggregate(catch.p~area~species~month~year, species.prop,sum)

model.frame.default 中的错误(公式 = catch.p ~ 区域 ~ 物种 ~ 月 ~ : 对象不是矩阵

但无法弄清楚如何在此处正确应用此功能

有人知道怎么做吗?

谢谢一百万!!

【问题讨论】:

  • 改用aggregate(catch.p~area+species+month+year, species.prop,sum)

标签: r dataframe aggregate multiple-columns


【解决方案1】:

在 R 中使用 dplyr 包。

species.prop %>% group_by(species, area, month, year) %>% summarise(catch.p = sum(catch.p))

给出的数据,结果看起来像

来源:本地数据框 [6 x 5] 组:物种、地区、月份 [?]

  species   area month  year catch.p
   (fctr) (fctr) (dbl) (dbl)   (dbl)
1     hom     IV     4  1998   27.60
2     hom     VI     4  1998   17.50
3     hom     VI     4  2000   40.25
4     pil     VI     4  1998    8.05
5     pil    VII     1  2000   46.00
6     pil    VII     5  1998   17.50

但是为了告诉你这是如何工作的,我将原始数据中的第6行更改为Area = VII和month = 5,它看起来像

来源:本地数据框 [5 x 5] 组:物种、地区、月份 [?]

  species   area month  year catch.p
   (fctr) (fctr) (dbl) (dbl)   (dbl)
1     hom     IV     4  1998   27.60
2     hom     VI     4  1998   17.50
3     hom     VI     4  2000   40.25
4     pil    VII     1  2000   46.00
5     pil    VII     5  1998   25.55

【讨论】:

    猜你喜欢
    • 2019-12-18
    • 1970-01-01
    • 2021-07-24
    • 1970-01-01
    • 2020-09-24
    • 1970-01-01
    • 1970-01-01
    • 2023-03-29
    • 2022-11-10
    相关资源
    最近更新 更多