如何将“1987年1月”字符串转换为Date对象?

我有几个月给出的数据,并希望将它们转换为日期对象。如何将“1987年1月”字符串转换为Date对象?

我试过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

回答:

假设你想要的月初(以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"

以上是 如何将“1987年1月”字符串转换为Date对象? 的全部内容, 来源链接: utcz.com/qa/265545.html

回到顶部