在R中将数值转换为yyyymm日期 [英] Converting numeric values to yyyymm dates in r

查看:101
本文介绍了在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"))

这篇关于在R中将数值转换为yyyymm日期的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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