r - Apply + lubridate returns numeric -
i have data set looks
birds[,1:3] source: local data frame [15 x 3] year month day 1 2015 5 13 2 2015 5 14 3 2015 5 15 4 2015 5 16 5 2015 5 17 6 2014 5 28 7 2014 5 29 8 2014 5 30 9 2014 5 31 10 2014 6 1 11 2013 5 8 12 2013 5 9 13 2013 5 10 14 2013 5 11 15 2013 5 12 what combine these columns 1 "date" column, figured paste them , pass them lubridate.
this works:
ymd(paste(birds[1,1], birds[1,2], birds[1,3], sep="-")) [1] "2015-05-13 utc" but when try use apply every row this:
apply(birds[,c("year","month","day")], 1, function(x) ymd(paste(x[1], x[2], x[3], sep="-"))) [1] 1431475200 1431561600 1431648000 1431734400 1431820800 1401235200 1401321600 1401408000 1401494400 [10] 1401580800 1367971200 1368057600 1368144000 1368230400 1368316800 why happen , how fix it?
we don't need apply margin=1. instead, can paste columns with(birds, paste(year, month, day, sep="-")) , wrap as.date convert 'date' class. output of ymd posixct class, within apply, coerced 'numeric' form.
library(lubridate) library(dplyr) mutate(birds, date=ymd(paste(year, month, day))) or can use unite tidyr , convert posixct class
library(tidyr) unite(birds, date, year:day, sep="-") %>% mutate(date=ymd(date)) or using do.call base r ymd
birds$date <- ymd(do.call(paste, birds)) or can use as.date base r
as.date(do.call(paste, c(birds,sep="-"))) to fix output obtained apply
res <- apply(birds[,c("year","month","day")], 1, function(x) ymd(paste(x[1], x[2], x[3], sep="-"))) unname(as.posixct(res, origin='1970-01-01',tz='utc')) #[1] "2015-05-13 utc" "2015-05-14 utc" "2015-05-15 utc" "2015-05-16 utc" #[5] "2015-05-17 utc" "2014-05-28 utc" "2014-05-29 utc" "2014-05-30 utc" #[9] "2014-05-31 utc" "2014-06-01 utc" "2013-05-08 utc" "2013-05-09 utc" #[13] "2013-05-10 utc" "2013-05-11 utc" "2013-05-12 utc" data
birds <- structure(list(year = c(2015l, 2015l, 2015l, 2015l, 2015l, 2014l, 2014l, 2014l, 2014l, 2014l, 2013l, 2013l, 2013l, 2013l, 2013l ), month = c(5l, 5l, 5l, 5l, 5l, 5l, 5l, 5l, 5l, 6l, 5l, 5l, 5l, 5l, 5l), day = c(13l, 14l, 15l, 16l, 17l, 28l, 29l, 30l, 31l, 1l, 8l, 9l, 10l, 11l, 12l)), .names = c("year", "month", "day"), class = "data.frame", row.names = c("1", "2", "3", "4", "5", "6", "7", "8", "9", "10", "11", "12", "13", "14", "15"))
Comments
Post a Comment