嗨,我对集合函数有个问题。我的数据如下:
transect_id year day month LST precipitation
1 TR001 2010 191 4 30.62083 0.0000
2 TR001 2010 191 4 30.62083 0.0003
3 TR001 2010 191 5 30.62083 0.0001
4 TR001 2010 191 7 30.62083 0.0000
5 TR001 2010 191 7 30.62083 0.0000
6 TR001 2011 191 7 30.62083 0.0007我想把每年每个季度的降水量相加。这意味着:每年1至3个月、4-6个月、7-9个月和10-12个月的总降水量(我的例子是2010-2013年)。并为它添加一列。我想我应该使用plyr包中的mutate()-function,然后执行以下操作
weather_gam.mutated<-mutate(weather_gam, precipitation.spring=aggregate(precipitation by = list(Category=year)))但这几个月该怎么办呢?我就是搞不懂。我尝试过像by = list(Category= month==1)这样的东西,但很明显,这并不是成功的必要条件。基本上,我只是尝试做SUMIFS(F1:Fx, B1:Bx = "2010", D1:Dx = "1", D1:Dx = "2", D1:Dx = "3"在Excel中所做的事情,只是希望通过设置
by = list(Category=year)当一年是相同的时候,它会自动地加和,所以我不需要每年手动地做它。我非常感谢这里的任何帮助,如果你有一个完全不同的想法如何解决它。
发布于 2015-07-17 14:36:42
下面是一个使用dplyr和lubridate的解决方案;其思想是使用lubridate的quarter函数来找出哪个季度属于哪个月。创建Quarter列,按季度分组,并为每个组创建Sum或precipitation。
library(lubridate)
library(dplyr)
df$month <- month(df$month)
df %>% mutate(Quarter = quarter(month)) %>% group_by(Quarter) %>% mutate(SumPre = sum(precipitation))
Source: local data frame [6 x 8]
Groups: Quarter
transect_id year day month LST precipitation Quarter SumPre
1 TR001 2010 191 4 30.62083 0e+00 2 4e-04
2 TR001 2010 191 4 30.62083 3e-04 2 4e-04
3 TR001 2010 191 5 30.62083 1e-04 2 4e-04
4 TR001 2010 191 7 30.62083 0e+00 3 7e-04
5 TR001 2010 191 7 30.62083 0e+00 3 7e-04
6 TR001 2011 191 7 30.62083 7e-04 3 7e-04在这里,使用aggregate的另一种方法
library(lubridate)
df$month <- month(df$month)
df$Quarter <- quarter(df$month)
aggregate(precipitation ~ Quarter, data = df, sum)
Quarter precipitation
1 2 4e-04
2 3 7e-04数据
df <- structure(list(transect_id = structure(c(1L, 1L, 1L, 1L, 1L,
1L), .Label = "TR001", class = "factor"), year = c(2010L, 2010L,
2010L, 2010L, 2010L, 2011L), day = c(191L, 191L, 191L, 191L,
191L, 191L), month = c(4L, 4L, 5L, 7L, 7L, 7L), LST = c(30.62083,
30.62083, 30.62083, 30.62083, 30.62083, 30.62083), precipitation = c(0,
3e-04, 1e-04, 0, 0, 7e-04)), .Names = c("transect_id", "year",
"day", "month", "LST", "precipitation"), row.names = c("1", "2",
"3", "4", "5", "6"), class = "data.frame")发布于 2015-07-17 14:44:40
使用dplyr代替plyr:
library(dplyr)
d.in %>%
mutate(q=cut(month, c(0,3,6,9,12), labels=c("q1", "q2", "q3", "q4"))) %>%
group_by(year, q) %>%
mutate(sum.prec = sum(precipitation))https://stackoverflow.com/questions/31477647
复制相似问题