r - Split date into different columns for year, month and day -
i have zoo objects like:
head(obs)
index pp 1932-01-01 0 1932-01-02 0.2 1932-01-03 0
and want split index 3 columns (years, months , days in separate columns) can analyses per day of month using ddply
.
i don't know if makes difference dates created using:
dates <- as.date(cet[,1], "%d-%m-%y") obs <- xts(cet[,2], dates)
where cet original file dates in column 1 , pp in column 2.
thanks helping!
1) columns. can use lubridate's year
/month
/day
or chron's month.day.year
:
1a) columns via lubridate
library(zoo) z <- zoo(1:1000, as.date("1932-01-01") + 0:999) library(lubridate) tt <- time(z) zz <- cbind(z, year = year(tt), month = month(tt), day = day(tt))
1b) columns via chron
library(zoo) z <- zoo(1:1000, as.date("1932-01-01") + 0:999) library(chron) zz <- with(month.day.year(time(z)), zoo(cbind(z, day, month, year)))
2) aggregate. however, not need create columns in first place. can use aggregate.zoo
directly original zoo object, z
, using lubridate or chron or using yearmon
zoo depending on want do:
2a) aggregate using lubridate
library(zoo) z <- zoo(1:1000, as.date("1932-01-01") + 0:999) library(lubridate) aggregate(z, day, mean) aggregate(z, month, mean) aggregate(z, year, mean)
2b) aggregate using chron
library(zoo) z <- zoo(1:1000, as.date("1932-01-01") + 0:999) library(chron) mdy <- month.day.year(time(z)) aggregate(z, mdy$day, mean) aggregate(z, mdy$month, mean) aggregate(z, mdy$year, mean) # or ct <- as.chron(time(z)) aggregate(z, days(ct), mean) aggregate(z, months(ct), mean) aggregate(z, years(ct), mean) # days(ct) , years(ct) can # shortened days , years within above context # (and work months except out of order) aggregate(z, days, mean) aggregate(z, years, mean)
2c) aggregate using yearmon
if wish summarize each year/month rather lumping january months together, february months together, etc. need neither chron nor lubridate rather can use zoo's yearmon
:
library(zoo) z <- zoo(1:1000, as.date("1932-01-01") + 0:999) aggregate(z, yearmon, mean)
Comments
Post a Comment