简体   繁体   中英

Converting characters to dates

In R, it seems like this should be obvious, but I'm having trouble. I have dates formatted as 1/1/00, 12/31/00, etc., where each part is abbreviated.

When I try to convert it to a date, I get this error:

> headlines$Date <- as.Date(headlines$Date)
Error in charToDate(x) : 
  character string is not in a standard unambiguous format

I've also tried the below, but get all NA s:

> headlines$Date <- as.Date(headlines$Date,format="%b/%d/%y")

How should I convert this column to dates?

Replace format = "%b/%d/%y" with format = "%m/%d/%y" .

%b means month as in Jan , Feb , Mar and so on.

%m is the integer equivalent ( 1 , 2 , 3 etc).

Further reading: https://www.stat.berkeley.edu/~s133/dates.html

You were on the right track by adding the format argument. I'm guessing you realized that the first error ("character string is not in a standard unambiguous format") happened because R doesn't know which of the numbers is the day, month, or the year. Say one of the values was "01/02/03"; there's no way of knowing whether it's 2 January 2003, or 1 February 2003, and so on.

In this case I think you just need to fix what you're passing to the format argument. %b is the symbol for abbreviated month in text form, not number form (eg "Jan" instead of "01"). You need to use %m instead for months stored as numbers. Try this:

headlines$Date <- as.Date(headlines$Date,format="%m/%d/%y")

See this page for more info about date formats in R.

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