【发布时间】:2022-12-27 22:40:18
【问题描述】:
I'm trying to change the date format in R. I have a data frame and one of the columns contains dates (as strings) in given format: Jan 11, 2002 but I would like to change the format to (also as string): 2002-01-11
I have tried many things, but nothing seems to work. My best shot was trying to convert it to Data object and then convert it back to string, but in different format.
Here is a piece of my code:
df$date = strftime(as.Date(df$date, format="%b %d, %Y"), "%Y-%m-%d")
I was trying other ways, but the result is always NA or a string, but in 'old' format.
I think there is something wrong with the first format: "%b %d, %Y", because when I tried the same thing but with different input, e.g. 11/01/2002 ("%d/%m/%Y") everything worked just fine.
I'm pretty new to R so any help would be appreciated.
【问题讨论】:
-
Doesn't this:
strftime(as.Date('Jan 11, 2002', format="%b %d, %Y"), "%Y-%m-%d")give you what you want? Besides you need to convert to date format first in order to be able to reformat it