无法使用as.Date格式化月份 [英] Unable to format months with as.Date

查看:93
本文介绍了无法使用as.Date格式化月份的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我在as.Date的格式部分缺少一些明显的东西。考虑这个例子



d1< - data.frame(d = c(1 / Jan / 1947,
1 / / 1947年2月/ 1947年,
d2 = c(Jan / 1947,
Feb / 1947,
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>

所以我的问题很简单 - 我不明白为什么date1工作,但date2不'

解决方案

最简单的答案是日期是包含一天的日期,如果没有指定日期,则为日期()变得困惑。从?as.Date文档中:


如果日期字符串没有完全指定日期,则
返回的答案可能是系统特定。最常见的行为是
,假设失踪的年,月或日是当前的。
如果它指定日期不正确,可靠的实现将
给出错误,并将日期报告为NA。不幸的是,
一些常见的实现(如glibc)是不可靠的,并且
根据预期的含义猜测。


当你想到这个时候,一个诸如1947年3月的术语绝对不是一个日期 - 这只是一个月份和一年的组合。日期是1947年3月(或任何其他月份+年)的特定日期,因为您没有指定日期,您没有日期。


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.

解决方案

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.

这篇关于无法使用as.Date格式化月份的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆