r - Moving averages -
i have daily data on 100 years looks
01.01.1856 12 02.01.1956 9 03.01.1956 -12 04.01.1956 7 etc.
i wish calculate 30 year running average huge data. tried converting data time series cant still figure out how go it. prefer simple method has working data.frame.
i guess preparation difficulty considering leapyears. try show way preparing, before using mentioned function runmean
of package require(catools)
. first create example data (which not necessary you, understanding). second divide data frame list of data frames, 1 each year , taking mean values each year. these 2 steps done @ once, think separated way easier understand , adapt.
#example data days <- seq(as.date("1958-01-01"), as.date("2015-12-31"), by="days") values <- runif(length(days)) df <- data.frame(days = days, values = values) #start of script years <- format(df$days, "%y") uniqueyears <- unique(format(df$days, "%y")) #create subset of years #look every unique year element of days in year. yearlysubset <- lapply(uniqueyears, function(x){ df[which(years == x), ] }) yearlymeanvalues <- sapply(yearlysubset, function(x){ mean(x$values) })
now running mean applied:
#install.packages("catools") require(catools) rm <- data.frame(years = uniqueyears, runningmean30y = runmean(yearlymeanvalues, 30))
just if didn't got right @ first , want running mean every day within 30 years, of course do:
rm <- cbind(df, runmean(df$values, 365 * 30))
and considering problems creating timeseries:
df[ , 1] <- as.date(df[ , 1], format = "%y.%m.%d")
Comments
Post a Comment