我只需要使用我的数据集中可用的最后一天到 aggregate 稍后但我没有成功......
library(tibbletime)
dataset <- data.frame(
timestamp = c("2010-01-01", "2010-01-03", "2010-01-23")
var = c( 1, 4, 11)
)
monthly_dataset <- as_tbl_time(dataset, index = timestamp) %>%
as_period("1 month")
我如何使用某些函数或 R 包来 aggregate 我的数据集仅用于使用最后一天可用?
回答1
Julian 的回答是一个不错的开始,但它不会跨越多年,因为分组变量不包含有关年份的信息。
执行此操作的典型方法是按年月分组,然后过滤到每个年月组的最大 date。
另外,作为 tibbletime 的创建者,我强烈建议您不再使用它。它已被弃用,不再受支持。你应该只使用时钟/lubridate 来处理 date 以及像 dplyr 这样的 tidyverse 包,或者如果你真的需要全部使用 time series,你应该使用 tsibble。
library(lubridate)
library(dplyr)
dataset <- tibble(
timestamp = c(
"2010-01-01", "2010-01-03", "2010-01-23",
"2010-02-01", "2010-02-03", "2011-02-23"
),
var = c(1, 4, 11, 1, 4, 11)
)
dataset <- mutate(dataset, timestamp = ymd(timestamp))
dataset <- dataset %>%
mutate(
year_month = floor_date(timestamp, "month"),
day = day(timestamp)
)
dataset %>%
group_by(year_month) %>%
filter(day == max(day)) %>%
ungroup()
#> # A tibble: 3 × 4
#> timestamp var year_month day
#> <date> <dbl> <date> <int>
#> 1 2010-01-23 11 2010-01-01 23
#> 2 2010-02-03 4 2010-02-01 3
#> 3 2011-02-23 11 2011-02-01 23
由 https://reprex.tidyverse.org (v2.0.1) 于 2022-05-18 创建
回答2
一个选项可以是 lubridate
包,例如
library(lubridate)
library(dplyr)
dataset <- data.frame(
timestamp = c("2010-01-01", "2010-01-03",
"2010-01-23", "2010-02-01", "2010-02-03", "2010-02-23"),
var = c(1, 4, 11, 1, 4, 11)
)
dataset %>%
mutate(month = timestamp %>% ymd() %>% month()) %>%
group_by(month) %>%
slice_tail()
结果:
# A tibble: 2 x 3
# Groups: month [2]
timestamp var month
<chr> <dbl> <dbl>
1 2010-01-23 11 1
2 2010-02-23 11 2