【问题标题】:Finding the first day of specific months in R在 R 中查找特定月份的第一天
【发布时间】:2014-07-12 15:26:29
【问题描述】:

我目前有一个列“月”和一个列“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))))

【问题讨论】:

    标签: r date if-statement


    【解决方案1】:

    好吧,如果没有可重现的示例,我无法提出完整的解决方案,但这里有一种方法可以生成每个月的第一个星期三日期。在这个例子中,我从 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 找到的答案改编了这段代码。

    【讨论】:

      【解决方案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 之间这一事实,并且显然只有这样的一天。您可以对第 2、3、4 个星期三进行类似操作,将条件更改为相应的,例如 DayMonth &gt; 7 &amp; DayMonth &lt; 15

      【讨论】:

      • @Frank 啊,你说得对!我现在更正了我的答案。
      • 我真的很喜欢你如何使用子集来做到这一点,这很有意义。我将把它合并到我的代码中,让查找特定日期变得非常容易。再次感谢。
      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2017-02-07
      • 2022-01-24
      • 2021-09-12
      相关资源
      最近更新 更多