Skip to contents

Applies a dplyr slice inside a time-based period (window).

Usage

slice_period(.data, ..., .date_var, .period = "1 day")

Arguments

.data

A tbl object or data.frame

...

For slice(): <data-masking> Integer row values.

Provide either positive values to keep, or negative values to drop. The values provided must be either all positive or all negative. Indices beyond the number of rows in the input are silently ignored.

For slice_*(), these arguments are passed on to methods.

.date_var

A column containing date or date-time values. If missing, attempts to auto-detect date column.

.period

A period to slice within. Time units are grouped using lubridate::floor_date() or lubridate::ceiling_date().

The value can be:

  • second

  • minute

  • hour

  • day

  • week

  • month

  • bimonth

  • quarter

  • season

  • halfyear

  • year

Arbitrary unique English abbreviations as in the lubridate::period() constructor are allowed:

  • "1 year"

  • "2 months"

  • "30 seconds"

Value

A tibble or data.frame

See also

Time-Based dplyr functions:

Examples

# Libraries
library(dplyr)

# First 5 observations in each month
m4_daily %>%
    group_by(id) %>%
    slice_period(1:5, .period = "1 month")
#> .date_var is missing. Using: date
#> # A tibble: 1,612 × 3
#> # Groups:   id [4]
#>    id    date       value
#>    <fct> <date>     <dbl>
#>  1 D10   2014-07-03 2076.
#>  2 D10   2014-07-04 2073.
#>  3 D10   2014-07-05 2049.
#>  4 D10   2014-07-06 2049.
#>  5 D10   2014-07-07 2006.
#>  6 D10   2014-08-01 1923.
#>  7 D10   2014-08-02 1957.
#>  8 D10   2014-08-03 1956.
#>  9 D10   2014-08-04 1999.
#> 10 D10   2014-08-05 2003.
#> # ℹ 1,602 more rows

# Last observation in each month
m4_daily %>%
    group_by(id) %>%
    slice_period(n(), .period = "1 month")
#> .date_var is missing. Using: date
#> # A tibble: 323 × 3
#> # Groups:   id [4]
#>    id    date       value
#>    <fct> <date>     <dbl>
#>  1 D10   2014-07-31 1917.
#>  2 D10   2014-08-31 1921.
#>  3 D10   2014-09-30 2024.
#>  4 D10   2014-10-31 2130 
#>  5 D10   2014-11-30 2217.
#>  6 D10   2014-12-31 2328.
#>  7 D10   2015-01-31 2210.
#>  8 D10   2015-02-28 2293.
#>  9 D10   2015-03-31 2392.
#> 10 D10   2015-04-30 2368.
#> # ℹ 313 more rows