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.
Method 1: Using as.POSIXct() method A string type date object can be converted to POSIXct object, using them as. POSIXct(date) method in R. “ct” in POSIXct denotes calendar time, it stores the number of seconds since the origin. It takes as input the string date object and the format specifier.
You can use the as. Date( ) function to convert character data to dates. The format is as. Date(x, "format"), where x is the character data and format gives the appropriate format.
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.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With