OP 已请求将 Year-Mon(没有月份中的某一天)从 data.frame 列转换为 Date,这是一个因素。如果没有日期,则日期不完整,会产生NAs。
有多种选项可用于处理不完整的日期。
as.Date() 补充了月份中的某天
正如d.b 以类似形式建议的那样:
as.Date(paste0(hand$date, "-01"), "%y-%b-%d")
#[1] "2014-01-01" "2014-02-01" "2014-03-01" "2015-01-01"
lubridate::ymd()
lubridate 包的ymd() 函数有一个truncated 参数来解析不完整的日期:
lubridate::ymd(hand$date, truncated = 1L)
#[1] "2014-01-01" "2014-02-01" "2014-03-01" "2015-01-01"
请注意,lubridate 自动假定为每个月的第一天。
zoo::as.yearmon() 和 zoo::as.Date()
Sagar 和statoptim 已经建议使用zoo 包中的as.yearmon() 函数的选项。
Sagan 的答案不完整,因为 as.yearmon() 返回的是 yearmon 类的对象,而不是 Date:
str(zoo::as.yearmon(hand$date, "%y-%b"))
#Class 'yearmon' num [1:4] 2014 2014 2014 2015
statoptim 的答案过于复杂,因为yearmon 可以直接强制转换为Date:
zoo::as.Date(zoo::as.yearmon(hand$date, "%y-%b"))
#[1] "2014-01-01" "2014-02-01" "2014-03-01" "2015-01-01"
请注意,如果我们没有预先加载zoo,我们必须使用zoo::as.Date(),因为base R 的as.Date() 不知道如何处理yearmon 对象。
zoo::as.Date() 默认自动假定为每个月的第一天。 frac 参数可用于控制返回月份中的哪一天,例如,
zoo::as.Date(zoo::as.yearmon(hand$date, "%y-%b"), frac = 1)
#[1] "2014-01-31" "2014-02-28" "2014-03-31" "2015-01-31"
返回每个月的最后一天。
警告
当前语言环境可能会影响对缩写月份名称的解释(statoptim's answer 中可能就是这种情况)。
There's an answer 到一个相关问题,建议查看?as.Date 的示例部分:
## read in date info in format 'ddmmmyyyy'
## This will give NA(s) in some locales; setting the C locale
## as in the commented lines will overcome this on most systems.
## lct <- Sys.getlocale("LC_TIME"); Sys.setlocale("LC_TIME", "C")
x <- c("1jan1960", "2jan1960", "31mar1960", "30jul1960")
z <- as.Date(x, "%d%b%Y")
## Sys.setlocale("LC_TIME", lct)
z