简体   繁体   中英

R apply function returns numeric value on date variables

I have a R dataframe which have sequence of dates. I want to create a dataframe from the existing one which consists of one month prior dates. For example let x be the initial dataframe

x = data.frame(dt = c("28/02/2000","29/02/2000","1/03/2000","02/03/2000"))

My required dataframe y would be

y = c("28/01/2000","29/01/2000","1/02/2000","02/02/2000")

The list is quite big so I don't want looping. I have created a inline function which works fine when I give individual dates.

datefun <- function(x) seq(as.Date(strptime(x,format = "%d/%m/%Y")), length =2, by = "-1 month")[2]

datefun("28/02/2000") gives "28/01/2000" as an output

But while I use it inside R apply it gives random numerical values.

apply(x,1,function(x) datefun(x))

The output for this is

[1] 10984 10985 10988 10989

I don't know from where these numbers are getting generated, am I missing something.

You could also skip your function with lubridate :

require(lubridate)
format(dmy(x$dt) %m+% months(-1),"%d/%m/%Y")

I believe that R internally is storing your dates as time elapsed since the UNIX epoch, which is January 1, 1970. You can easily view your updated dates as readable strings using as.Date with an apporpriate origin, eg

y <- apply(x,1,function(x) datefun(x))
as.Date(y, origin='1970-01-01')

[1] "2000-01-28" "2000-01-29" "2000-02-01" "2000-02-02"

The gist here is that the numerical output you saw perhaps misled you into thinking that your date information were somehow lost. To the contrary, the dates are stored in a numerical format, and it is up to you to tell R how you want to view that information as dates.

Demo

You should not use apply since the result will be returned as a matrix. Matrices in R cannot store values of class Date . You have to use lapply instead. This returns a list of results. These results can be combined with Reduce and c to create a Date vector.

Reduce(c, lapply(x$dt, datefun))
# [1] "2000-01-28" "2000-01-29" "2000-02-01" "2000-02-02"

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM