Home > Enterprise >  Use %/% within a pipe
Use %/% within a pipe

Time:07-20

I would like to get interval in days as an integer between two dates:

library(tidyverse) # esp for lubridate

date1 <- ymd('2022-01-01')
date2 <- ymd('2022-01-10')
day_interval <- interval(date1, date2)
day_interval %/% days() # returns 9

But I want to combine the 2 last lines into one. Is this possible? Tried e.g:

day_interval <- interval(date1, date2) |> %/% days()
Error: unexpected SPECIAL in "day_interval <- interval(date1, date2) |> %/%"

How can I do the whole think in a oner using a pipe?

CodePudding user response:

We could use

interval(date1, date2) %/% days() 
[1] 9

Or may also use

interval(date1, date2) %>% 
  `%/%`(., days())
[1] 9

Or with |>

interval(date1, date2) |> 
   {\(x) x %/% days()}()
[1] 9

Or using %>%

interval(date1, date2) %>%
   {. %/% days()}
[1] 9

CodePudding user response:

You could skip the pipe like this:

library(lubridate)
date1 <- ymd('2022-01-01')
date2 <- ymd('2022-01-10')
day_interval <- interval(date1, date2) %/% days()
day_interval
#> [1] 9

Created on 2022-07-19 by the reprex package (v2.0.1)

Different option is using difftime:

library(lubridate)
date1 <- ymd('2022-01-01')
date2 <- ymd('2022-01-10')
difftime(date1 ,date2 , units = c("days"))
#> Time difference of -9 days

Created on 2022-07-19 by the reprex package (v2.0.1)

  • Related