Home > Enterprise >  In a single chain get a max date - n years
In a single chain get a max date - n years

Time:11-30

(Better title wording recommendations welcome)

pacman::p_load(tidyverse, fable, fpp3, feasts)
aus_livestock$Month |> max() |> as_date()
[1] "2018-12-01"

I want to get this date minus 6 years in one line. Tried:

aus_livestock$Month |> max() |> as_date() |> -years(6)
Error: function '-' not supported in RHS call of a pipe

Then tried curly braces {}:

aus_livestock$Month |> max() |> as_date() |> {. -years(6)}
Error: function '{' not supported in RHS call of a pipe

This does work:

x <- aus_livestock$Month |> max() |> as_date()
x - years(6)
[1] "2012-12-01"

But this involves saving an intermediary variable x. I'd prefer to do it in a oner if there's a way?

CodePudding user response:

We could use a lambda function

aus_livestock$Month |>
    max() |> 
    as_date() |> 
    (\(x) x - years(6))()
[1] "2012-12-01"
  • Related