This is a thin wrapper around a lubridate::floor_date() that works for hms, yearmon, and yearqtr classes as well.

floor_index(x, unit = "seconds")

Arguments

x

a vector of date-time objects

unit

a string, Period object or a date-time object. When a singleton string, it specifies a time unit or a multiple of a unit to be rounded to. Valid base units are second, minute, hour, day, week, month, bimonth, quarter, season, halfyear and year. Arbitrary unique English abbreviations as in the period() constructor are allowed. Rounding to multiples of units (except weeks) is supported. When unit is a Period object, units of the period objects are used. This is equivalent to converting the period object to its string representation and passing as unit argument.

When unit is a date-time object rounding is done to the nearest of the elements in unit. If range of unit vector does not cover the range of x ceiling_date() and floor_date() round to the max(x) and min(x) for elements that fall outside of range(unit).

Examples


data(FB)
dplyr::mutate(FB, date2 = floor_index(date, "year"))
#> # A tibble: 1,008 × 9
#>    symbol date        open  high   low close    volume adjusted date2     
#>    <chr>  <date>     <dbl> <dbl> <dbl> <dbl>     <dbl>    <dbl> <date>    
#>  1 FB     2013-01-02  27.4  28.2  27.4  28    69846400     28   2013-01-01
#>  2 FB     2013-01-03  27.9  28.5  27.6  27.8  63140600     27.8 2013-01-01
#>  3 FB     2013-01-04  28.0  28.9  27.8  28.8  72715400     28.8 2013-01-01
#>  4 FB     2013-01-07  28.7  29.8  28.6  29.4  83781800     29.4 2013-01-01
#>  5 FB     2013-01-08  29.5  29.6  28.9  29.1  45871300     29.1 2013-01-01
#>  6 FB     2013-01-09  29.7  30.6  29.5  30.6 104787700     30.6 2013-01-01
#>  7 FB     2013-01-10  30.6  31.5  30.3  31.3  95316400     31.3 2013-01-01
#>  8 FB     2013-01-11  31.3  32.0  31.1  31.7  89598000     31.7 2013-01-01
#>  9 FB     2013-01-14  32.1  32.2  30.6  31.0  98892800     31.0 2013-01-01
#> 10 FB     2013-01-15  30.6  31.7  29.9  30.1 173242600     30.1 2013-01-01
#> # … with 998 more rows

time_test <- create_series('00:00:00'~'12:00:00',
                           '1 minute', class = "hms")

dplyr::mutate(time_test, date2 = floor_index(date, "hour"))
#> # A time tibble: 721 × 2
#> # Index:         date
#>    date   date2 
#>    <time> <time>
#>  1 00'00" 00'00"
#>  2 01'00" 00'00"
#>  3 02'00" 00'00"
#>  4 03'00" 00'00"
#>  5 04'00" 00'00"
#>  6 05'00" 00'00"
#>  7 06'00" 00'00"
#>  8 07'00" 00'00"
#>  9 08'00" 00'00"
#> 10 09'00" 00'00"
#> # … with 711 more rows