简体   繁体   中英

convert factor variable into date

Suppose I have a variable as x with in the data frame z, which is a factor, but I want it to convert into date.

x <- factor(c("17.05.2016","19.05.2016","42472","42481"))
y <- 1:4
z <- data.frame(x,y)
z

I tried with the following code but I am getting the result partially correct.Could you please help me with this problem.

z$x1 = tryCatch({
z$x = as.Date(z$x ,origin = "1899-12-30")
},error = function(e){
z$x =as.Date(z$x, "%d.%M.%Y")
})
z

It works but it's not a trycatch

z$x1 <- as.Date(z$x, format="%d.%m.%Y")
z$x1[is.na(z$x1)] <- as.Date(as.numeric(as.character(z$x[is.na(z$x1)])) ,origin = "1899-12-30")

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