我如何获得每个月的数量?

How do i get the number of each month?

我有一个包含一列日期对象的数据框。我怎样才能得到一个包含月份数的新列? 示例:一月 -> 1,二月 -> 2 ...

我也需要一个包含每个月每一天的数字的新列。 示例:2022-01-01 -> 1 , 2022-01-02 - 2

我确定 R 中有日期 object-specific 解决方案,但我从未使用过它们。基础 R 解决方案:

splitDates <- function( date ) {
  
  day <- gsub('^0+','',unlist(strsplit(date,'-'))[2])
  month <- gsub('^0+','',unlist(strsplit(date,'-'))[3])
  
  return(list(day,
              month))
  
}

您可以使用以下代码:

df = data.frame(date = as.Date(c("2022-01-01", "2022-01-02")))
df[, "month"] <- format(df[,"date"], "%m")
df

输出:

        date month
1 2022-01-01    01
2 2022-01-02    01
require(tidyverse)
require(lubridate) 

示例数据:

# A tibble: 13 × 1
   date      
   <date>    
 1 2022-04-28
 2 2022-05-28
 3 2022-06-28
 4 2022-07-28
 5 2022-08-28
 6 2022-09-28
 7 2022-10-28
 8 2022-11-28
 9 2022-12-28
10 2023-01-28
11 2023-02-28
12 2023-03-28
13 2023-04-28

可能的解决方案:

  df %>%
  mutate(
    month = month(date),
    month_name = month(date, label = TRUE, abbr = FALSE),
    day = day(date),
    week = week(date)
  )

输出:

# A tibble: 13 × 5
   date       month month_name   day  week
   <date>     <dbl> <ord>      <int> <dbl>
 1 2022-04-28     4 April         28    17
 2 2022-05-28     5 May           28    22
 3 2022-06-28     6 June          28    26
 4 2022-07-28     7 July          28    30
 5 2022-08-28     8 August        28    35
 6 2022-09-28     9 September     28    39
 7 2022-10-28    10 October       28    43
 8 2022-11-28    11 November      28    48
 9 2022-12-28    12 December      28    52
10 2023-01-28     1 January       28     4
11 2023-02-28     2 February      28     9
12 2023-03-28     3 March         28    13
13 2023-04-28     4 April         28    17