我有使用R测量降水的数据。我的日期格式为 2008-01-01,范围为 10 年。我正在尝试从 2008-10-01 聚合到 2009-09-31,但我不确定如何。有没有办法在聚合中设置聚合和组的开始日期。
我当前的代码是
data<- aggregate(data$total_snow_cm, by=list(data$year), FUN = 'sum')
但是这个输出给了我从 1 月 - 12 月每年降雪的总和,但我希望它包括 10 月/08 到 9 月/09
假设您的数据是长格式的,我会做这样的事情:
library(tidyverse)
#make sure R knows your dates are dates - you mention they're 'yyyy-mm-dd', so
yourdataframe <- yourdataframe %>%
mutate(yourcolumnforprecipdate = ymd(yourcolumnforprecipdate)
#in this script or another, define a water year function
water_year <- function(date) {
ifelse(month(date) < 10, year(date), year(date)+1)}
#new wateryear column for your data, using your new function
yourdataframe <- yourdataframe %>%
mutate(wateryear = water_year(yourcolumnforprecipdate)
#now group by water year (and location if there's more than one)
#and sum and create new data.frame
wy_sums <- yourdataframe %>% group_by(locationcolumn, wateryear) %>%
summarize(wy_totalprecip = sum(dailyprecip))
欲了解更多信息,请阅读tidyverse
伟大的子库lubridate
-ymd()
函数来自何处。还有其他像ymd_hms()
. mutate()
来自整洁宇宙的dplyr
图书馆。这两个库都非常有用!
给出这个问题的实际答案,其中提出了aggregate()
的方式。
您可以使用 with()
将数据规范包装在 aggregate()
周围。在with()
中,您可以像使用数字一样定义日期间隔。
df1.agg <- with(df1[as.Date("2008-10-01") <= df1$year & df1$year <= as.Date("2009-09-30"), ],
aggregate(total_snow_cm, by=list(year), FUN=sum))
另一种方法是使用 aggregate()
的公式接口,其中 data
因此,也可以在aggregate()
调用中指定间隔。
df1.agg <- aggregate(total_snow_cm ~ year,
data=df1[as.Date("2008-10-01") <= df1$year &
df1$year <= as.Date("2009-09-30"), ], FUN=sum)
结果
head(df1.agg)
# year total_snow_cm
# 1 2008-10-01 171
# 2 2008-10-02 226
# 3 2008-10-03 182
# 4 2008-10-04 129
# 5 2008-10-05 135
# 6 2008-10-06 222
数据
set.seed(42)
df1 <- data.frame(total_snow_cm=sample(120:240, 4018, replace=TRUE),
year=seq(as.Date("2000-01-01"),as.Date("2010-12-31"), by="day"))