How to transform a dataframe of characters to the respective dates?

后端 未结 2 2076
無奈伤痛
無奈伤痛 2020-12-21 14:03

I noticed already a couple of times that working with dates doesn\'t allow for using the usual tricks in R. Say I have a dataframe Data with Dates (see below), and I want to

相关标签:
2条回答
  • 2020-12-21 14:47

    How about

    str(as.data.frame(lapply(Data,as.Date,format="%d %B %Y")))
    # 'data.frame':   6 obs. of  4 variables:
    #  $ Rep1:Class 'Date'  num [1:6] 12898 12898 13907 13907 13907 ...
    #  $ Rep2:Class 'Date'  num [1:6] 13278 13278 14217 14217 14217 ...
    #  $ Rep3:Class 'Date'  num [1:6] 13600 13600 14340 14340 14340 ...
    #  $ Rep4:Class 'Date'  num [1:6] 13831 13831 14669 14669 14669 ...
    
    0 讨论(0)
  • 2020-12-21 15:03

    I think the most succinct way to do this is:

    Data[] <- lapply(Data, as.Date,format="%d %B %Y")
    

    This also nicely generalises to the case where not all columns are dates:

    Data[date_col] <- lapply(Data[date_col], as.Date,format="%d %B %Y")
    

    You can also simplify the date parsing with a couple of other packages

    library(stringr)
    library(lubridate)
    Data[] <- lapply(Data, function(x) dmy(str_trim(x)))
    

    which is a little more verbose, but has the advantage that you don't need to figure out the data format yourself.

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