如何标记上个星期五或最后一个或几个月 [英] How to flag last friday or last day or month
问题描述
我有一个数据框架的日期和星期几
I have a data frame of dates and the day of the week
> head(data)
day weekday
1 2016-01-01 Friday
4 2016-01-04 Monday
5 2016-01-05 Tuesday
6 2016-01-06 Wednesday
7 2016-01-07 Thursday
8 2016-01-08 Friday
这里是代码:
data <- data.frame(day = seq(as.Date("2014-01-01"), as.Date("2016-05-10"), "day"),
weekday = weekdays(seq(as.Date("2014-01-01"), as.Date("2016-05-10"),
"day")))
excludeDays <- c("Saturday", "Sunday")
data <- subset(data, !weekdays(data$day) %in% excludeDays) #exclude weekend
我想添加2个列,标记每个月的最后一个星期五和该月的最后一天,不管它是什么日子。你会怎么做?
I would like to add 2 columns that flag the last friday in each month and the last day in the month regardless of what day it is. How would you do that?
更具体地说:
我想要识别,只有我的数据,如果日期是最后一个日期这个月。例如,如果我的数据在2016年1月的日期和1月份的最后日期是1/20,那么应该被标记为该月的最后一天。同样,我想确定一个月的最后一个星期五,我的数据不在日历上。
To be more specific: I would like it to identify, only for my data, if the date is the last date in the month. For example, if my data has dates in January 2016 and the last date in January I have is 1/20/2016 then that should be flagged as the last day in the month. Similarly I'd like to identify the last Friday in a month in my data not on a calendar.
推荐答案
附加说明并且遵循@eminik的评论
With the additional clarification and following the comment by @eminik the code below
library(data.table)
setDT(data)
data[, LastDayInMonth := day == max(day), by = .(year(day), month(day))]
data[, LastFridayInMonth := weekday == "Friday" & day == max(day),
by = .(year(day), month(day), weekdays(day))]
产生:
# show results (only relevant rows)
data[LastDayInMonth | LastFridayInMonth == TRUE]
day weekday LastDayInMonth LastFridayInMonth
1: 2016-01-29 Friday TRUE TRUE
2: 2016-02-26 Friday FALSE TRUE
3: 2016-02-29 Monday TRUE FALSE
4: 2016-03-25 Friday FALSE TRUE
5: 2016-03-31 Thursday TRUE FALSE
6: 2016-04-29 Friday TRUE TRUE
7: 2016-05-06 Friday FALSE TRUE
8: 2016-05-10 Tuesday TRUE FALSE
编辑:修改代码以说明OP所要求的更改年数。
Code modified to account for change of years as requested by OP.
注意: 工作日
在使用的区域中返回名称为的字符向量。因此,代码仅在您处于英文区域时才起作用。否则,您可能必须使用 Sys.setlocale(category =LC_ALL,locale =English)
。
Note: weekdays
returns a character vector of names in the locale in use. Therefore, the code only works if you are in an English locale. Otherwise, you may have to use Sys.setlocale(category = "LC_ALL", locale = "English")
before.
这篇关于如何标记上个星期五或最后一个或几个月的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!