代码之家  ›  专栏  ›  技术社区  ›  statwoman

计算r中的月天数

  •  0
  • statwoman  · 技术社区  · 2 年前

    我有一个数据框,列名为 date 结构如下所示。请注意,这是我的数据帧的一个小示例。我有不同的月份和年份(我的主要日期范围是从2005年1月3日到2021 12月31日)。我想计算每个月和年份组合中的天数,即2005-12年为2天,2006-01年为3天。如何得到这些计数的向量?

    df$date <- as.Date(c(
    "2005-12-28", "2005-12-31", "2006-01-01", "2006-01-02", "2006-01-03", "2006-02-04", "2007-03-02", "2007-03-03", "2007-03-06", "2007-04-10", "2007-04-11"))
    
    2 回复  |  直到 2 年前
        1
  •  1
  •   Jon Spring    2 年前
    library(dplyr)
    
    df %>%
      # distinct(date) %>% # unnecessary if no dupe dates
      mutate(month = lubridate::floor_date(date, "month")) %>%
      count(month)
    

    后果

           month n
    1 2005-12-01 2
    2 2006-01-01 3
    3 2006-02-01 1
    4 2007-03-01 3
    5 2007-04-01 2
    

    使用的数据:

    df <- structure(list(date = structure(c(13145, 13148, 13149, 13150, 
    13151, 13183, 13574, 13575, 13578, 13613, 13614), class = "Date")), row.names = c(NA, 
    -11L), class = "data.frame")
    
        2
  •  0
  •   Niranjan Poudel    2 年前

    df %>% mutate(date = format(.$date, "%Y-%m")) %>% group_by(date) %>% count(date) -> out

    out以tibble的形式按年份和月份为您提供摘要。

        3
  •  0
  •   Mohamed Desouky    2 年前

    这是另一个解决方案,

    a <- as.Date(c("2005-12-28", "2005-12-31", "2006-01-01",
      "2006-01-02", "2006-01-03", "2006-02-04",
      "2007-03-02", "2007-03-03", "2007-03-06",
      "2007-04-10", "2007-04-11"))
    
    date <- strsplit(as.character(a) , "-")
    # to extract months
    months <- lapply(date , function(x) x[2])
    # to extract years
    years <- lapply(date , function(x) x[1])
    
    table(unlist(months))
    #> 
    #> 01 02 03 04 12 
    #>  3  1  3  2  2
    
    table(unlist(years))
    #> 
    #> 2005 2006 2007 
    #>    2    4    5
    

    创建日期:2022-06-01 reprex package (v2.0.1)