找到R中特定月份的第一天

时间:2014-07-12 15:26:30

标签: r date if-statement

我目前有一个专栏“月”&列出“DayWeek”列,列出一周中的一个月和一天。使用下面的代码,我可以在2月,5月,8月和2月的每个星期三得到一个1的列。 11月我正在努力寻找一种方法来获得一个1s的专栏,就在我刚才提到的4个月的第一个星期三。任何想法或我是否必须为它创建一个循环?

testPrices$Rebalance <- ifelse((testPrices$Month=="February" & testPrices$DayWeek == "Wednesday"),1,ifelse((testPrices$Month=="May" & testPrices$DayWeek == "Wednesday"),1,ifelse((testPrices$Month=="August" & testPrices$DayWeek == "Wednesday"),1,ifelse((testPrices$Month=="November" & testPrices$DayWeek == "Wednesday"),1,0))))

2 个答案:

答案 0 :(得分:4)

嗯,没有一个可重复的例子,我无法想出一个完整的解决方案,但这里有一种方法可以生成每个月的第一个星期三日期。在这个例子中,我从2013年1月1日开始,出去36个月,但你可以找出适合你的东西。然后,您可以检查此处生成的第一个星期三向量,以查看您的日期是否是月份组的第一个星期三的成员,并指定1,如果是的话。

# I chose this as an origin
orig <- "2013-01-01"

# generate vector of 1st date of the month for 36 months
d <- seq(as.Date(orig), length=36, by="1 month")

# Use that to make a list of the first 7 dates of each month
d <- lapply(d, function(x) as.Date(seq(1:7),origin=x)-1) 

# Look through the list for Wednesdays only, 
# and concatenate them into a vector
do.call('c', lapply(d, function(x) x[strftime(x,"%A")=="Wednesday"]))

输出:

 [1] "2013-01-02" "2013-02-06" "2013-03-06" "2013-04-03" "2013-05-01" "2013-06-05" "2013-07-03"
 [8] "2013-08-07" "2013-09-04" "2013-10-02" "2013-11-06" "2013-12-04" "2014-01-01" "2014-02-05"
[15] "2014-03-05" "2014-04-02" "2014-05-07" "2014-06-04" "2014-07-02" "2014-08-06" "2014-09-03"
[22] "2014-10-01" "2014-11-05" "2014-12-03" "2015-01-07" "2015-02-04" "2015-03-04" "2015-04-01"
[29] "2015-05-06" "2015-06-03" "2015-07-01" "2015-08-05" "2015-09-02" "2015-10-07" "2015-11-04"
[36] "2015-12-02"

注意:我根据herehere找到的答案调整了此代码。

答案 1 :(得分:2)

我创建了一个样本数据集,可以像这样工作(谢谢@Frank!):

orig <- "2013-01-01"
d <- data.frame(date=seq(as.Date(orig), length=1000, by='1 day'))
d$Month <- months(d$date)
d$DayWeek <- weekdays(d$date)
d$DayMonth <- as.numeric(format(d$date, '%d'))

从这样的数据框中,您可以使用subset提取特定月份的第一个星期三,如下所示:

subset(d, Month %in% c('January', 'February') & DayWeek == 'Wednesday' & DayMonth < 8)

这利用了日数(1..31)总是在1到7之间的事实,显然正好会有一天这样。你可以在第三,第三,第四个星期三做同样的事情,相应地改变条件,例如DayMonth > 7 & DayMonth < 15