查找本月的第一个星期二 [英] Find first Tuesday of Month
问题描述
我正在尝试编写一个将日期向量作为输入并返回日期向量的函数-其中输出是与输入日期匹配的月份的第一个星期二的日期.
I am trying to write a function which takes a vector of dates as an input and returns a vector of dates -- where the output is the date of the first Tuesday of the month which matches the input date.
所以 2012-11-19
-> 2012-11-06
等
我在一次约会中就取得了一些成功,但无法归纳为向量案例.有人可以帮忙吗?
I have had some success with a single date, but have not been able to generalise to the vector case. Could someone please help?
这是我到目前为止所拥有的:
This is what I have so far:
firstTuesday <- function(tt){
ct <- as.POSIXct(tt)
lt <- as.POSIXlt(tt)
firstOf <- as.POSIXlt(ct - 60*60*24* (lt$mday - 1))
if (firstOf$wday > 2)
{
adjDays <- (9 - firstOf$wday)
firstTues <- as.POSIXlt(as.POSIXct(firstOf) + 60*60*24*adjDays)
}
else {
adjDays <- (2 - firstOf$wday)
firstTues <- as.POSIXlt(as.POSIXct(firstOf) + 60*60*24*adjDays)
}
return(firstTues)
}
哪个日期适用于单个日期: firstTuesday(Sys.Date())
,但对日期向量产生了垃圾(由于 if
不是矢量化控件的问题,运营商,我认为).
Which works for a single date: firstTuesday(Sys.Date())
but yielded junk for vectors of dates (due to issues with if
not being a vectorised control operator, i think).
我通过使用索引避开了我有限的理解.以下代码似乎可以解决问题.
I got around my limited understanding by using indexing. The following code seems to do the trick.
firstTuesday <- function(tt){
ct <- as.POSIXct(tt)
lt <- as.POSIXlt(tt)
firstOf <- as.POSIXlt(ct - 60*60*24* (lt$mday - 1))
firstTue <- as.POSIXct(firstOf)
idx <- firstOf$wday > 2
firstTue[idx] <- as.POSIXct(firstOf[idx]) + 60*60*24*(9 - firstOf$wday[idx])
firstTue[!idx] <- as.POSIXct(firstOf[!idx]) + 60*60*24*(2 - firstOf$wday[!idx])
return(firstTue)
}
推荐答案
这使用lubridate并使逻辑更简单.给定一个日期向量,第二个函数将返回一个字符向量,类似于您的输入.您可以根据自己的需要进行更改.
This uses lubridate and makes the logic a little simpler. Given a vector of dates the second function will return a vector of characters, similar to your input. You can change things around to suit your needs.
library(lubridate)
getTuesday = function(x) {
date = ymd(x)
first = floor_date(date,"month")
dow = sapply(seq(0,6),function(x) wday(first+days(x)))
firstTuesday = first + days(which(dow==3)-1)
return(firstTuesday)
}
getMultipleTuesdays = function(y) {
tmp = lapply(y, getTuesday)
tmp = lapply(tmp, as.character)
return(unlist(tmp))
}
编辑
样本输入/输出
getMultipleTuesdays(c("2012-11-19","2012-11-19","2011-01-15"))
[1] "2012-11-06" "2012-11-06" "2011-01-04"
这篇关于查找本月的第一个星期二的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!