简体   繁体   English

在r中计算月份中的天数

[英]Counting number of days in months in r

I have a dataframe with a column named date structured as bellow.我有一个数据框,其中包含一个名为date的列,其结构如下。 Note that this is a small sample of my dataframe.请注意,这是我的数据框的一个小样本。 I have different months and different years (my main date range is from 2005-01-03 to 2021-12-31).我有不同的月份和不同的年份(我的主要日期范围是从 2005-01-03 到 2021-12-31)。 I want to count the number of days in each month and year combination ie 2 days in 2005-12, 3 days in 2006-01, ... .我想计算每个月和年组合中的天数,即 2005-12 年的 2 天,2006-01 年的 3 天,...。 How can I get a vector of these counts?如何获得这些计数的向量?

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)

Result结果

       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

Data used:使用的数据:

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 为您提供按年和月作为小标题的摘要。

Here is another solution ,这是另一种解决方案,

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

Created on 2022-06-01 by the reprex package (v2.0.1)reprex 包于 2022-06-01 创建 (v2.0.1)

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM