Today's integer data frame in R

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

19820509 19550503 20080505 19590505 19940517 19690504 20050420 20060503 19840427 19550513 

We will call it df.

I tried several different lines of code to simply change each value in the date format to R as follows: "1982-05-09"

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

not working and

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

or

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

I keep getting the error "I don’t know how to convert" df "to the class" date "or to any of the POSIX formats.

I thought it would be easier. Any ideas?

Thanks.

+7
source share
3 answers

You need to reference specific columns, and not just refer to a data frame. If a variable containing integer dates is in the df data frame 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 integers to character strings, and then interprets the strings as dates.

If you have several columns containing dates in this format, you can convert them in one fell swoop, but you should do it a little differently:

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

Or even better, since docendo discimus is mentioned in the comment:

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

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

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

This package provides more functions for parsing data or rows by date, ymd (y = year, m = month, d = day) with this simple scheme.

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

data$DATE - date of the column transfer in integer format, for example 20000131 , 20000201

0
source

Source: https://habr.com/ru/post/986177/


All Articles