我有几个月的数据,并希望将它们转换为日期对象。
我试过as.Date(as.character(data$Date), format = '%Y %B'
没有成功。怎么解决这个问题?
代码&数据
> head(SE.10Y)
Date SE.10Y
1 1987 January 11.7385
2 1987 February 11.5000
3 1987 March 11.2586
4 1987 April 11.2385
5 1987 May 11.8153
6 1987 June 11.8120
> dput(droplevels(head(SE.10Y)))
structure(list(Date = structure(c(3L, 2L, 5L, 1L, 6L, 4L), .Label = c("1987 April",
"1987 February", "1987 January", "1987 June", "1987 March", "1987 May"
), class = "factor"), SE.10Y = c(11.7385, 11.5, 11.2586, 11.2385,
11.8153, 11.812)), .Names = c("Date", "SE.10Y"), row.names = c(NA,
6L), class = "data.frame")
> as.Date(as.character(head(SE.10Y)$Date), format = '%Y %B')
[1] NA NA NA NA NA NA
答案 0 :(得分:1)
假设你想要月初(以UTC为单位)并使用lubridate
,你会得到:
dates <- c("1987 April", "1987 February", "1987 January", "1987 June", "1987 March", "1987 May")
lubridate::ymd(paste(dates,"01"))
[1] "1987-04-01 UTC" "1987-02-01 UTC" "1987-01-01 UTC" "1987-06-01 UTC" "1987-03-01 UTC" "1987-05-01 UTC"