Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
508 views
in Technique[技术] by (71.8m points)

r - Unable to format months with as.Date

I'm missing something obvious with the "format" section of as.Date. Consider this example

d1 <- data.frame(d = c("1/Jan/1947", "1/Feb/1947", "1/Mar/1947"), d2 = c("Jan/1947", "Feb/1947", "Mar/1947"))

d1$date1 <- as.Date(x=d1$d, format="%d/%b/%Y")
d1$date2 <- as.Date(x=d1$d2, format="%b/%Y")

           d       d2      date1 date2
1 1/Jan/1947 Jan/1947 1947-01-01  <NA>
2 1/Feb/1947 Feb/1947 1947-02-01  <NA>
3 1/Mar/1947 Mar/1947 1947-03-01  <NA>

so my question is really simple -- I don't understand why the date1 works but date2 doesn't.

See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Answer

0 votes
by (71.8m points)

The simplest answer is that a date is something which includes a day and if one is not specified, as.Date() gets confused. From the ?as.Date documentation:

If the date string does not specify the date completely, the returned answer may be system-specific. The most common behaviour is to assume that a missing year, month or day is the current one. If it specifies a date incorrectly, reliable implementations will give an error and the date is reported as ‘NA’. Unfortunately some common implementations (such as ‘glibc’) are unreliable and guess at the intended meaning.

When you think about it, a term such as "Mar/1947" is not, strictly speaking, a date - it's just a combination of month and year. A date is a specific day in March 1947 (or any other month + year) - since you don't specify one, you don't have a date.


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...