简体   繁体   中英

as.date in R does not convert years properly

I import the csv file:

{casesRaw<-read.csv('CasesRaw.csv')
tail(casesRaw$Date)

my result:

"12/28/2020" "12/29/2020" "12/30/2020" "12/31/2020" "1/1/2021"   "1/2/2021"

after conversion:

casesRaw$Date<-as.Date(casesRaw$Date,"%m/%d/%y")
tail(casesRaw$Date)

my result is:

[1] "2020-12-28" "2020-12-29" "2020-12-30" "2020-12-31" "2020-01-01" "2020-01-02"

as you can see still I have 2020-01-01, .... Any Idea?

We need %Y for 4-digit year instead of %y which is for 2-digit year

casesRaw$Date <- as.Date(casesRaw$Date, "%m/%d/%Y")

Here is another base R option using gsub

casesRaw$Date <- as.Date(gsub("(.*)/(.*)", "\\2/\\1", casesRaw$Date))

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