我有使用R每天测量降水量的数据。我的日期格式为2008-01-01,范围为10年。我正在尝试从2008年10月1日到2009年9月31日汇总,但不确定如何。汇总中是否可以设置汇总和分组的开始日期。
我当前的代码是
data<- aggregate(data$total_snow_cm, by=list(data$year), FUN = 'sum')
但是此输出为我提供了从1月到12月的每年降雪量的总和,但我希望它包括oct / 08到9月/ 09。
答案 0 :(得分:0)
假设您的数据为长格式,我将执行以下操作:
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()
来自tidyverse的dplyr
库。这两个库都非常有用!
答案 1 :(得分:0)
我想在提出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"))