如何使用 R 从一个月的日期中获取周数
How to get week number from one month dates using R
输入:
Dates
2012-02-01
2012-02-07
2012-02-15
2012-02-22
2012-02-28
期望的输出:
Dates
Month_Of_Week
2012-02-01
1
2012-02-07
2
2012-02-13
3
2012-02-15
3
2012-02-21
4
2012-02-22
4
2012-02-28
5
df$week_in_month <- 1 +
ceiling(as.numeric(difftime(as.Date(df$Input_Dates),
as.Date(paste0(substr(df$Input_Dates,1,8),'01')), units = "weeks")))
输出为:
Input_Dates week_in_month
1 2012-02-01 1
2 2012-02-07 2
3 2012-02-15 3
4 2012-02-22 4
5 2012-02-28 5
示例数据:
df <- structure(list(Input_Dates = c("2012-02-01", "2012-02-07", "2012-02-15",
"2012-02-22", "2012-02-28")), .Names = "Input_Dates", class = "data.frame", row.names = c(NA,
-5L))
输入:
Dates |
---|
2012-02-01 |
2012-02-07 |
2012-02-15 |
2012-02-22 |
2012-02-28 |
期望的输出:
Dates | Month_Of_Week |
---|---|
2012-02-01 | 1 |
2012-02-07 | 2 |
2012-02-13 | 3 |
2012-02-15 | 3 |
2012-02-21 | 4 |
2012-02-22 | 4 |
2012-02-28 | 5 |
df$week_in_month <- 1 +
ceiling(as.numeric(difftime(as.Date(df$Input_Dates),
as.Date(paste0(substr(df$Input_Dates,1,8),'01')), units = "weeks")))
输出为:
Input_Dates week_in_month
1 2012-02-01 1
2 2012-02-07 2
3 2012-02-15 3
4 2012-02-22 4
5 2012-02-28 5
示例数据:
df <- structure(list(Input_Dates = c("2012-02-01", "2012-02-07", "2012-02-15",
"2012-02-22", "2012-02-28")), .Names = "Input_Dates", class = "data.frame", row.names = c(NA,
-5L))