1) Create columns of the Date class, and then easily. External packages are not used:
asDate <- function(x) as.Date(x, "1970-01-01") my.data2 <- transform(my.data, date1 = as.Date(ISOdate(YEAR1, MONTH1, DAY1)), date2 = as.Date(ISOdate(YEAR2, MONTH2, DAY2)) ) transform(my.data2, mean.date = asDate(rowMeans(cbind(date1, date2))))
If we added the library(zoo) call, we could omit the definition of asDate using as.Date in the last line instead of asDate , since zoo adds the default beginning to as.Date .
1a) The dplyr version will look like this (using asDate above):
library(dplyr) my.data %>% mutate( date1 = ISOdate(YEAR1, MONTH1, DAY1) %>% as.Date, date2 = ISOdate(YEAR2, MONTH2, DAY2) %>% as.Date, mean.date = cbind(date1, date2) %>% rowMeans %>% asDate)
2) Another method uses julian in the chron package. julian converts month / day / year to the number of days from the Age. We can average two Julian and return to the Date class:
library(zoo) library(chron) transform(my.data, mean.date = as.Date( ( julian(MONTH1,DAY1,YEAR1) + julian(MONTH2,DAY2,YEAR2) )/2 ) )
We could omit library(zoo) if instead of as.Date use asDate from (1).
Update Discussed use of the zoo to reduce decisions and further reduce decisions (1).