我有一個資料框,其中有一列名為以下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"))
uj5u.com熱心網友回復:
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")
uj5u.com熱心網友回復:
df %>% mutate(date = format(.$date, "%Y-%m")) %>% group_by(date) %>% count(date) -> out
out 為您提供按年和月作為小標題的摘要。
uj5u.com熱心網友回復:
這是另一種解決方案,
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 包于 2022-06-01 創建(v2.0.1)
轉載請註明出處,本文鏈接:https://www.uj5u.com/houduan/484073.html
上一篇:具有長url-param的Vue3路由器(包括特殊字符)無法按預期作業?
下一篇:如何使今天的日期等于特定日期?
