在R中将数值转换为yyyymm日期
我正在尝试隐藏以下日期格式。我在lubridate包和strfttime函数中使用parse_date_time遇到了麻烦,因为它要么将整个列转换为同一日期,要么因为它一直在返回日值。我不想在解决方案中看到任何日期。
I am trying to covert the following date formats. I have run into trouble using parse_date_time in lubridate package and the strfttime function since it either converts the entire column to the same date or because it keeps on returning the day value. I don't want to see any dates in my solution.
mydata=data.frame(dates=c(200102,200102,200111,200202),desired=c('2001-02','2001-02', '2001-11','2002-02'))
我只想在我的栏中返回YYYY-mm格式。我在执行此操作时遇到了麻烦。我尝试使用
I want to return just the YYYY-mm format in my column. I am having trouble doing this. I have tried using
尝试一下:
transform(mydata, desired = sub("(....)(..)", "\\1-\\2", dates))
这种形式的操作不方便(绘图等)。您可能更喜欢使用zoo软件包中的 yearmon
类,该类在内部将年/月存储为年+小数,其中1月的小数是0,2月的小数是1/12 ,...,Dec的11/12。输出时的默认渲染例如是 2000年1月
:
This form is not that convenient for manipulation (plotting, etc.). You might prefer to use the "yearmon"
class from the zoo package which stores internally the year/months as year + fraction where fraction is 0 for Jan, 1/12 for Feb, ..., 11/12 for Dec. On output the default rendering is, for example, Jan 2000
:
library(zoo)
transform(mydata, ym = as.yearmon(as.character(dates), "%Y%m"))