在 R 中查找特定月份的第一天

Tre*_*lof 4 if-statement r date

我目前有一列“月”和一列“DayWeek”,其中写出了一周中的月份和日期。使用下面的代码,我可以在 2 月、5 月、8 月和 11 月的每个星期三获得一个带有 1 的列。我正在努力寻找一种方法,仅在我刚刚提到的 4 个月中的每个月的第一个星期三获得一个带有 1 的列. 有什么想法还是我必须为它创建一个循环?

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))))
Run Code Online (Sandbox Code Playgroud)

Jot*_*ota 5

好吧,如果没有可重现的示例,我无法提出完整的解决方案,但这里有一种方法可以生成每个月的第一个星期三日期。在此示例中,我从 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"]))
Run Code Online (Sandbox Code Playgroud)

输出:

 [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"
Run Code Online (Sandbox Code Playgroud)

注意:我根据此处此处找到的答案改编了此代码。


Sto*_*ica 3

我创建了一个示例数据集来像这样使用(感谢@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'))
Run Code Online (Sandbox Code Playgroud)

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

subset(d, Month %in% c('January', 'February') & DayWeek == 'Wednesday' & DayMonth < 8)
Run Code Online (Sandbox Code Playgroud)

这利用了这样一个事实:日期数字 (1..31) 始终在 1 到 7 之间,并且显然只有一个这样的日期。您可以对第二个、第三个、第四个星期三执行类似的操作,相应地将条件更改为DayMonth > 7 & DayMonth < 15