[R] interpolation to montly data

Miguel Manese jjonphl at gmail.com
Sat Jun 16 19:45:35 CEST 2012


Hi Ken, Stef,

We can make your script more elegant like below:


On Sun, Jun 17, 2012 at 12:52 AM, Ken <katakagi at bu.edu> wrote:
>
> stef salvez <loggyedy <at> googlemail.com> writes:

[snip]


> #load library
> library(plyr)
>
> # utility function
> mean.var = function(df, var){ mean(df[[var]], na.rm = T)};
>
> # create example data
> dat <- data.frame("country" = c(rep(1,8), rep(2, 8)),
>                 "date" = c("23/11/08","28/12/08","25/01/09","22/02/09",
>                          "29/03/09","26/04/09","24/05/09", "28/06/09",
>                          "26/10/08","23/11/08","21/12/08","18/01/09",
>                          "15/02/09","16/03/09","12/04/09","10/05/09"),
>                 "price" = c(2,3,4,5,6,32,23,32,45,46,90,54,65,77,7,6))
> # add month column to df
> dat$month = substr(dat$date, 4,5)

dat <- transform(dat, date=as.Date(date, "%d/%m/%y"))
dat <- transform(dat, month=as.numeric(format(date, "%m")))

>
> #calculate average price by month across all countries and calculate
> monthly
> #frequency and put output in one data frame
> monthly.price = ddply(dat, .(month), mean.var, var = "price")
> monthly.price = cbind(monthly.price, "month.freq" =
> as.vector(table(df$month)))
> names(monthly.price) = c("month", "average.price", "month.freq")

# by country & month
ddply(dat, .(country, month), function(x) c(avg.price=mean(x$price),
freq=nrow(x)))

# by country & year-month
library(zoo)
dat <- transform(dat, yearmon=as.yearmon(date))
ddply(dat, .(country, yearmon), function(x) c(avg.price=mean(x$price),
freq=nrow(x)))

Regards,
- Jon



More information about the R-help mailing list