L.J
L.J

Reputation: 1084

How to apply a function for each year in R?

It is like I have a zoo object, and what I want to do is to apply a certain data manipulation/function for each year separately.

Is there any convenient way to accomplish the task?

Example data:

data <- zoo(rnorm(1000),as.Date("1973-02-01") + c(1:1000) - 1)

And mean values of each year needs to be calculated.

Upvotes: 0

Views: 687

Answers (2)

Swyler
Swyler

Reputation: 124

You can use the apply.yearly(x, FUN, ...) function from the xts library. It also works with zoo objects.

apply.yearly(data, mean)

Output:

 1973-12-31  1974-12-31  1975-10-28 
-0.01142834  0.02000210  0.02259480 

Upvotes: 0

Achim Zeileis
Achim Zeileis

Reputation: 17168

You can use the aggregate() method for zoo series. What exactly the aggregation function is depends on the class you use for the time index (e.g., yearmon or Date etc.). With some artificial data using yearmon:

set.seed(1)
x <- rnorm(36) + 1:36
z_yearmon <- zoo(x, as.yearmon(2000) + 1:36/12)
aggregate(z_yearmon, function(x) floor(as.numeric(x)), mean)
##      2000      2001      2002      2003 
##  6.257619 17.729362 29.258357 35.585005 

Instead of mean() you can plug in any other custom function. Or for Date index:

z_date <- zoo(x, as.Date(time(z_yearmon)))
aggregate(z_yearmon, function(x) 1900 + as.POSIXlt(x)$year, mean)
##      2000      2001      2002      2003 
##  6.257619 17.729362 29.258357 35.585005 

Upvotes: 4

Related Questions