计算 r 中以月为单位的天数

Counting number of days in months in r

我有一个数据框,其中包含一个名为 date 的列,结构如下。请注意,这是我的数据框的一小部分样本。我有不同的月份和不同的年份(我的主要日期范围是从 2005-01-03 到 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"))
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")

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

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

这是另一个解决方案,

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

reprex package (v2.0.1)

创建于 2022-06-01