如何使用R从一个月的日期获得周数

时间:2018-02-07 06:39:10

标签: r dataframe lubridate

输入 日期
2012-02-01
2012-02-07
2012-02-15
2012-02-22
2012-02-28

期望的输出:
日期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

1 个答案:

答案 0 :(得分:0)

希望这有帮助!

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))