从R中的日期中删除年份 [英] Remove year from dates in R

查看:457
本文介绍了从R中的日期中删除年份的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有20年的气象数据,但我只对每年的模式感兴趣。例如,我不在乎1995年6月与2011年6月有何不同。相反,我想在6月1日使用20个值,在6月2日使用20个值,等等。

I have 20 years worth of weather data, but I'm only interested in the patterns per year. I don't care how June 1995 is different from June 2011, for example. Instead, I want to have 20 values for June 1, 20 values for June 2, etc.

我的问题:如何删除日期对象的年份部分,保留月份和日期,同时还保留日期的顺序属性?我的最终目标是一长串重复的mm / dd值,每个值对应于结果变量。我将把mm / dd视为因子,但顺序正确。

My question: How do I drop the year portion of a date object, keep the month AND day, while also maintaining the sequential properties of dates? My ultimate goal is a long list of repeated mm/dd values corresponding each to the outcome variable. I'll treat the mm/dd like factors, but in the correct order.

# Given this:
as.Date(c("2014-06-01","1993-06-01", "2013-06-03", "1999-01-31"), "%Y-%m-%d")
# I want to get this:
"06-01" "06-01" "06-03" "01-31"
# That will sort like this
"01-31" "06-01" "06-01" "06-03"

小技巧使用sub()删除年份并将破折号转换为十进制不起作用,因为这时该月的1号与该月的10号相同。我还尝试过将日期转换成字符串,删除年份,然后将其转换回日期……这一切都使2014年成为现实。

Little hacks like using sub() to drop the year and convert the dash to a decimal doesn't work because then the 1st of the month is the same as the 10th of the month. I also tried turning the dates into character strings, removing the year, and then turning it back into a date... that just made everything year 2014.

推荐答案

这项工作吗?

temp<-as.Date(c("2014-06-01","1993-06-01", "2013-06-03", "1999-01-31"), "%Y-%m-%d")

x<-format(temp, format="%m-%d")

 x
[1] "06-01" "06-01" "06-03" "01-31"


sort(x)
[1] "01-31" "06-01" "06-01" "06-03"

这篇关于从R中的日期中删除年份的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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