DJ-AFC
DJ-AFC

Reputation: 569

Sum daily values into monthly values

I am trying to sum daily rainfall values into monthly totals for a record over 100 years in length. My data takes the form:

Year     Month     Day     Rain
1890       1        1         0
1890       1        2       3.1
1890       1        3       2.5
1890       1        4      15.2

In the example above I want R to sum all the days of rainfall in January 1890, then February 1890, March 1890.... through to December 2010. I guess what I'm trying to do is create a loop to sum values. My output file should look like:

Year    Month    Rain
1890      1       80.5
1890      2       72.4
1890      3       66.8
1890      4       77.2

Any easy way to do this?

Many thanks.

Upvotes: 1

Views: 2877

Answers (2)

J.R.
J.R.

Reputation: 3878

In some cases it can be beneficial to convert it to a time-series class like xts, then you can use functions like apply.monthly().

Data:

df <- data.frame(
  Year = rep(1890,5), 
  Month = c(1,1,1,2,2), 
  Day = 1:5,
  rain = rexp(5)
)

> head(df)
      Year Month Day      rain
    1 1890     1   1 0.1528641
    2 1890     1   2 0.1603080
    3 1890     1   3 0.5363315
    4 1890     2   4 0.6368029
    5 1890     2   5 0.5632891

Convert it to xts and use apply.monthly():

library(xts)
dates <- with(df, as.Date(paste(Year, Month, Day), format("%Y %m %d")))
myXts <- xts(df$rain, dates)

> head(apply.monthly(myXts, sum))
                [,1]
1890-01-03 0.8495036
1890-02-05 1.2000919

Upvotes: 0

cdeterman
cdeterman

Reputation: 19950

You can use dplyr for some pleasing syntax

library(dplyr)

df %>%
  group_by(Year, Month) %>%
  summarise(Rain = sum(Rain))

Upvotes: 3

Related Questions