date - R: Best way around as.POSIXct() in apply function -
i'm trying set new variable incorporates difference (in number of days) between known date , end of given year. dummy data below:
> date.event <- as.posixct(c("12/2/2000","8/2/2001"), format = "%d/%m/%y", tz = "europe/london") > year = c(2000,2001) > dates.test <- data.frame(date.event,year) > dates.test date.event year 1 2000-02-12 2000 2 2001-02-08 2001
i've tried applying function achieve this, returns error
> time.dif.fun <- function(x) { + as.numeric(as.posixct(sprintf('31/12/%s', s= x['year']),format = "%d/%m/%y", tz = "europe/london") - x['date.event']) + } > dates.test$time.dif <- apply( + dates.test, 1, time.dif.fun + ) error in unclass(e1) - e2 : non-numeric argument binary operator
it seems apply() not as.posixct(), testing version of function derives end of year date, returned numeric in form '978220800' (e.g. end of year 2000). there way around this? real data function bit more complex, including conditional instances using different variables , referring previous rows, hard without apply.
here alternatives:
1) code works these changes. factored out s, not because necessary, because following line gets hard read without due length. note if x
data frame x["year"]
x[["year"]]
vector x$year
. since operations vectorized not need apply
.
although have not made change, bit easier define s s <- paste0(x$year, "-12-31")
in case omit format argument in following line owing use of default format.
time.dif.fun <- function(x) { s <- sprintf('31/12/%s', x[['year']]) as.numeric(as.posixct(s, format = "%d/%m/%y", tz = "europe/london") -x[['date.event']]) } time.dif.fun(dates.test) ## [1] 323 326
2) convert posixlt, set year, month , day end of year , subtract. note year component uses years since 1900 , mon component uses jan = 0, feb = 1, ..., dec = 11. see ?as.posixlt
details on these , other components:
lt <- as.posixlt(dates.test$date.event) lt$year <- dates.test$year - 1900 lt$mon <- 11 lt$mday <- 31 as.numeric(lt - dates.test$date.event) ## [1] 323 326
3) possibility is:
with(dates.test, as.numeric(as.date(paste0(year, "-12-31")) - as.date(date.event))) ## [1] 323 326
wiki
Comments
Post a Comment