16

I have a data frame with 10 dates which I read into R as integers. Here is the data frame:

19820509
19550503
20080505
19590505
19940517
19690504
20050420
20060503
19840427
19550513

We'll called it df.

I have attempted a few different lines of code here to simply change each value to the date format in R like this: "1982-05-09"

df <-  as.Date(df, "%Y%m%d")

doesn't work and neither does

 df <- as.POSIXlt(df, format = "%Y/%m/%d")

or

df <- as.POSIXct(df), format = "%Y/%m/%d", origin = "19820509")

I keep getting an error saying "do not know how to convert 'df' to class "date" or either of the POSIX formats.

I thought this would be more simple. Any ideas?

Thank you.

user3720887
  • 719
  • 1
  • 11
  • 18

3 Answers3

18

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"))
Alex A.
  • 5,466
  • 4
  • 26
  • 56
7

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.

SabDeM
  • 7,050
  • 2
  • 25
  • 38
0
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

Rushabh Patel
  • 2,672
  • 13
  • 34