2016-07-14 134 views
0

我有几个月给出的数据,并希望将它们转换为日期对象。如何将“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 
+3

你需要每天有个约会。那些只是几个月和几年。我已经看到人们通过简单地粘贴1表示每月的第一天来完成日期,从而解决了这个问题。 'as.Date(paste(data $ Date,1),format =“%Y%B%d”)' –

+0

有没有什么办法可以将所有文本值(“January”)转换为数字?在这种情况下,我可以做一个yearmon变量,这将是很好的。 – uncool

+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"