Convert yyyymmdd string to Date class in R

后端 未结 4 2030
时光取名叫无心
时光取名叫无心 2020-11-29 07:03

I would like to convert these dates with format YYYYMMDD to a Date class.

dates <- data.frame(Date = c(\"20130707\", \"20130706\", \"20130705\", \"2013070         


        
相关标签:
4条回答
  • 2020-11-29 07:50

    Classic R:

    > start_numeric <- as.Date('20170215', format = '%Y%m%d');
    > start_numeric
    [1] "2017-02-15"
    > format(start_numeric, "%Y%m%d")
    [1] "20170215"
    
    0 讨论(0)
  • 2020-11-29 07:51

    You need to provide the Date column, not the entire data.frame.

    R> as.Date(dates[["Date"]], "%Y%m%d")
    [1] "2013-07-07" "2013-07-06" "2013-07-05" "2013-07-04"
    
    0 讨论(0)
  • 2020-11-29 08:01

    Use the lubridate package for an easy conversion:

    date_test <- data.frame(Date = c("20130707", "20130706", "20130705", "20130704"))
    date_test$Date <- ymd(date_test$Date)
    
    date_test
            Date
    1 2013-07-07
    2 2013-07-06
    3 2013-07-05
    4 2013-07-04
    
    0 讨论(0)
  • 2020-11-29 08:02

    An extra conversion to characters works for me:

    dates<-as.Date(as.character(dates),format="%Y%m%d")
    

    Without the conversion the following error occurs:

    dates<-as.Date(dates,format="%Y%m%d")
    Error in as.Date.numeric(dates, format = "%Y%m%d") : 
      'origin' must be supplied
    

    Different error but this might help, works for POSIXct too, paste date and hours, format %Y%m%d%H

    0 讨论(0)
提交回复
热议问题