integer data frame to date in R [duplicate] integer data frame to date in R [duplicate] r r

integer data frame to date in R [duplicate]


You have to reference specific columns rather than just referencing the data frame. If the variable containing the integer dates is in a data frame df and is called x, you can do this:

df <- transform(df, x = as.Date(as.character(x), "%Y%m%d"))#             x#  1 1982-05-09#  2 1955-05-03#  3 2008-05-05#  4 1959-05-05#  5 1994-05-17#  6 1969-05-04#  7 2005-04-20#  8 2006-05-03#  9 1984-04-27# 10 1955-05-13

This converts the integers to character strings, then interprets the strings as dates.

If you multiple columns containing dates in this format, you can convert them in one fell swoop, but you have to do it slightly differently:

df <- data.frame(lapply(df, function(x) as.Date(as.character(x), "%Y%m%d")))

Or even better, as docendo discimus mentioned in a comment:

df[] <- lapply(df, function(x) as.Date(as.character(x), "%Y%m%d"))


Here is my solution, it requires the lubridate package. You can use the ymd function of the lubridate package as a "replacement function". Just pick the column you want to convert ad replace it with the ymd version of it.

 library(lubridate) data[ , 1 ] <- ymd(data[, 1])

This package provides more functions to parse data or strings to dates, ymd (y = year, m = month, d= day) all with this simple scheme.


v = c(data$DATE)date <- as.Date(paste(v), format("%Y%m%d"))date

data$DATE is the column carrying date in integer format like 20000131, 20000201