我的数据栏看起来像......
date
<fctr>
14-Jan
14-Feb
14-Mar
15-Jan
只是想知道如何把它变成一个日期,因为当我打开这个代码时,我得到了NA的
hand$date <- as.Date(hand$date, format = "%y-%b")
date
<fctr>
NA
NA
NA
NA
感谢您的帮助!
答案 0 :(得分:3)
OP已要求将data-frame列中的Year-Mon(不包括日期)转换为Date,这是一个因素。没有月中的某天,日期不完整,产生NA
s。
有多种选择可以处理不完整的日期。
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()
ymd()
包的lubridate
函数有一个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已经建议使用as.yearmon()
包中zoo
功能的选项。
Sagan的答案不完整,因为as.yearmon()
会返回班级yearmon
但不会Date
的对象:
str(zoo::as.yearmon(hand$date, "%y-%b"))
#Class 'yearmon' num [1:4] 2014 2014 2014 2015
由于yearmon
可以直接强制转移到Date
,因此statoptim的答案不必要地复杂化:
zoo::as.Date(zoo::as.yearmon(hand$date, "%y-%b"))
#[1] "2014-01-01" "2014-02-01" "2014-03-01" "2015-01-01"
请注意,如果我们之前未加载zoo::as.Date()
,则必须使用zoo
,因为基础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
答案 1 :(得分:1)
以下工作。
> library(zoo)
> as.yearmon("14-Jan", "%y-%b")
[1] "Jan 2014"
答案 2 :(得分:0)
动物园包文档具有以下示例,该示例也在我的R
上返回NAzoo::as.yearmon("mar07", "%b%y")
我正在使用gsub替换&#34; Jan&#34;到&#34; 01&#34;。我发现这不是最有效的代码,但希望这对你有帮助。
library(zoo)
df = data.frame(date = c("14-Jan", "14-Feb", "15-Jan"), stringsAsFactors = F)
month.abb
# [1] "Jan" "Feb" "Mar" "Apr" "May" "Jun" "Jul" "Aug" ....
month.num = substr( paste0("0", c(1:12)), start=c(rep(1,9), rep(2,3)), stop=3)
head(month.num)
# [1] "01" "02" "03" "04" "05" "06"
# can't think of or find ways to vectorize gsub
for(i in 1:12) {
df$date = gsub(df$date, pattern=month.abb[i], replacement=month.num[i])
}
as.Date(as.yearmon(df$date, format = "%y-%m"))
# [1] "2014-01-01" "2014-02-01" "2015-01-01"