在R中更改为日期格式 [英] Changing to Date Format in R
本文介绍了在R中更改为日期格式的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
我有一个名为month的数据列,我想转换成日期格式
I have a data column called month which I want to convert into date format
在电子表格中,它的格式为Mar-07
In the spreadsheet, it's of the form Mar-07
但是当我尝试使用R转换它时:
But when I try to convert it in R using:
mydata$month<-as.Date(mydata$month, format = "%b-%y")
我得到NAs
我哪里错了?感谢
推荐答案
zoo
包含一个类 yearmon
,可以代表每月数据。这个类有一个 as.Date
方法。
The zoo
package has a class, yearmon
, which can represent monthly data. There is an as.Date
method for this class.
library(zoo)
ym <- as.yearmon("Mar-07", "%b-%y")
str(ym)
# Class 'yearmon' num 2007
将 yearmon
对象转换为类日期
:
date <- as.Date(ym)
date
# [1] "2007-03-01"
str(date)
# Date[1:1], format: "2007-03-01"
frac
参数可用于指示一个月的一小部分。默认的 frac
是0,即如上所述的月的第一天。
The frac
argument can be used to indicate a fraction of the month. The default frac
is 0, i.e. first day in month, as above.
as.Date(ym, frac = 0.5)
# [1] "2007-03-16"
as.Date(ym, frac = 1)
# [1] "2007-03-31"
这篇关于在R中更改为日期格式的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!
查看全文