我有数据。帧代表不同的年份。每年都有一个日期列。我想在每个变量中创建一个变量,它将一年中的前7天,第二个7天等分组。所以“2020-01-17”会在“01-15到01-21”中
#sample Data
x1 <- data.frame(
day=c("2020-02-21" ,"2020-01-19" ,"2020-01-30" ,"2020-01-17" ,"2020-02-18" ,"2020-02-31", "2020-02-21" ,"2020-01-02" ,"2020-01-28", "2020-02-27" ,"2020-02-29","2020-02-11" ,"2020-01-05", "2020-02-06", "2020-02-10", "2020-01-31" ,"2020-02-18"),
one = 1 )
x2 <- data.frame(
day=c("2021-02-21" ,"2021-01-19" ,"2021-01-30" ,"2021-01-17" ,"2021-02-18" ,"2021-02-31", "2021-02-21" ,"2021-01-02" ,"2021-01-28", "2021-02-27" ,"2021-02-29","2021-02-11" ,"2021-01-05", "2021-02-06", "2021-02-10", "2021-01-31" ,"2021-02-18"),
one = 1 )
我知道如何将天转换为周,但是如果我按照建议使用format
(Remove year from dates in R)删除年,它会生成一个字符,然后我就不能使用cut
了。
x2$day <- as.Date( x2$day , "%Y-%m-%d")
x1$day <- as.Date( x1$day , "%Y-%m-%d")
x1$day2 <- format( x1$day , "%m-%d")
class( x1$day2)
如果我不放弃年份,那么同一日期将在不同的星期结束。
using the cut function "2020-02-21", and "2021-02-21" are in different weeks. I want them to be in the same bin
cut(as.Date(x2$day), breaks="week")
cut(as.Date(x1$day), breaks="week")
2条答案
按热度按时间of1yzvn41#
如果这包括闰年和非闰年,那就不起作用了,因为一年中的第i天可能落在不同的日期范围内。我们能做的就是根据组号命名组。让我们把一年中的前14天记为0,接下来的14天记为1,以此类推。
给出:
dxxyhpgq2#
你在正确的道路上与
cut()
。使用跨越全年的每周序列,可以使用findInterval()
来查找与每个日期匹配的序列索引(即周数)。创建于2023-05-17带有reprex v2.0.2