将因子更改为R中的日期格式 [英] Change factor to a date format in R

查看:156
本文介绍了将因子更改为R中的日期格式的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有一个日期格式为 YYYY-mm 的文件。我正在准备我的数据进行时间序列分析,因此需要将格式从因子转换为 Date 格式。

I have a file with dates in the format YYYY-mm. I am trying to prepare my data for a time series analysis and therefore need to convert the formats from factor to a Date format.

我曾尝试过:

x <- '2011-11'
as.Date(as.character(a), "%Y-%m")

最后一行给我一个输出 NA

the last line gives me an output NA.

谢谢!

推荐答案

2011-11不是日期( )添加一天:

"2011-11" is not a date (where's the day)? Either add a day:

a <- '2011-11'
as.Date(paste0(a,'-01'))

或使用动物园的 yearmon class:

or use zoo's yearmon class:

library(zoo)
as.yearmon(a)

这篇关于将因子更改为R中的日期格式的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆