在R中指定ifelse语句中的日期范围 [英] work around to specifying date range in ifelse statement in R

查看:112
本文介绍了在R中指定ifelse语句中的日期范围的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在尝试在我的 data.frame 中使用 ifelse 语句在类 as.POSIXct 的日期列。

I am trying to create a new column denoting quarter in my data.frame using an ifelse statement on a date column of class as.POSIXct .

这是日期的简短版本

 a            

            spot.id local.date
q12014local.1  11824267 2013-12-30
q12014local.2  11825708 2013-12-30
q12014local.3  11823669 2013-12-30
q12014local.4  11825407 2013-12-30
q12014local.5  11824268 2013-12-30
q12014local.6  11825709 2013-12-30
q12014local.7  11823670 2013-12-30
q12014local.8  11825408 2013-12-30
q12014local.9  11824266 2013-12-31
q12014local.10 11825707 2013-12-31

这是我写的 ifelse 语句:
> a $ quarter< - ifelse(a $ local.date> = 2013-07-01& a $ local.date< = 2013-09-30,q32013​​,
ifelse(a $ local .date> = 2013-10-01& a $ local.date< = 2013-12-31,q42013​​,
ifelse(a $ local.date> = 2014-01-01& ; a $ local.date< = 2014-03-31,q12014,
ifelse(a $ local.date> = 2014-04-01& a $ local.date< = 2014- 06-30,q22014,ifelse(a $ local.date> = 2014-07-01& a $ local.date< = 2014-09-30,q32014,NA))))) / code>

This is the ifelse statement i wrote: > a$quarter <- ifelse(a$local.date >= 2013-07-01 & a$local.date <= 2013-09-30,"q32013", ifelse(a$local.date >= 2013-10-01 & a$local.date <= 2013-12-31 , "q42013", ifelse(a$local.date >= 2014-01-01 & a$local.date <= 2014-03-31, "q12014", ifelse(a$local.date >= 2014-04-01 & a$local.date <= 2014-06-30, "q22014", ifelse(a$local.date >= 2014-07-01 & a$local.date <= 2014-09-30, "q32014", NA)))))

由于某些原因,我所获得的是我的新列中的NA值!我可以使用 data.frame 中的row.names与 gsub a $ (< - gsub([\\。] [0-9] +,,row.names(a))但这不理想。如果 ifelse 是对日期对象进行排序,我尝试使用此帖子中的函数:,但没有解决。我还是得到NA值。实现我的目标是什么正确的方法?

For some reason, all I get is NA values in my new column ! I can use the row.names in my data.frame with a gsub like a$quarter <- gsub("[\\.][0-9]+", "", row.names(a)) but that's not ideal. If ifelse is unclassing date objects, I tried using the function from this post : How to prevent ifelse() from turning Date objects into numeric objects but that didn't work out. I still get NA values. What's the right way to achieve my objective ?

编辑:不知道许多功能,如季度 format.yearqtr 可在 zoo lubridate 中。但与此相关,如果我的宿舍与日历年份不一样 - 例如我的第一季度从10月开始,1月份的2月2日。

Was unaware of the numerous functions like quarters , format.yearqtr available in zoo and lubridate. But related to the same, what if my quarters are not the same as calendar year quarters - For e.g. My quarter 1 begins in October, quarter 2 in Jan etc.

推荐答案

不使用任何额外的包:

transform(dat,qu=paste0(quarters(local.date),format(local.date,'%Y')))

这篇关于在R中指定ifelse语句中的日期范围的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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