简体   繁体   中英

how to convert factor column into date in data frame in r

I have a data frame in r with the following structure:

TERMINAL_ID ACTION_DATE ACC_AMOUNT
1009162   02-JAN-18      14.30
1009162   02-JAN-18      21.45

and the class for 'action_date' is factor and I would to convert it to date. I tried this code but no success

dataf <- as.Date(as.character(data$ACTION_DATE),
                                format = "%d-%y-%Y")
fdate=as.POSIXlt(data$ACTION_DATE, "%d-%b-%y")
as.Date('02-JAN-18', format = '%d-%B-%y')

[1] "2018-01-02"

or by using lubridate

library(lubridate)
dmy("02-Jan-17")

this turns your character which holds the date in d(ays)m(onth)y(ear) into a Date format.

I have created vector x with date format you mentioned. Using the lubridate package, the solution was pretty straight forward.

x<- as.factor(c("02-JAN-18", "03-JAN-19", NA, "abc"))
lubridate::dmy(x)
#> Warning: 1 failed to parse.
#> [1] "2018-01-02" "2019-01-03" NA           NA

Created on 2018-10-01 by the reprex package (v0.2.1)

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM