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"))

Leave a Comment