0

How can I set the paramenter units ="mins" in the following function as a parameter?

This is just the data frame:

library(tidyverse)

u <- runif(10, 0, 60) 
w <- runif(10, 0, 60) 

df <- tibble(time_1 = as.POSIXct(u, origin = "2019-02-03 08:00:00"),
       time_2 = as.POSIXct(w, origin = "2019-02-03 08:30:00"))

This is my funtion. I would like to be able to change the paramenter for difftime and set it as a parameter, e.g. units = "months".

time_diff <- function(df, stamp1, stamp2){

  stamp1 <- enquo(stamp1)
  stamp2 <- enquo(stamp2)

  name <- paste0(quo_name(stamp1), "_", quo_name(stamp2))

  df %>% 
    mutate(!!name := difftime(!!stamp1, !!stamp2, units="mins"))
}

df %>% 
  time_diff(time_2, time_1)

But I would like something like this:

df %>% 
      time_diff(time_2, time_1, mins)
xhr489
  • 1,957
  • 13
  • 39

1 Answers1

1

What about just adding the units parameter? e.g.

time_diff <- function(df, stamp1, stamp2, units="mins"){

  stamp1 <- enquo(stamp1)
  stamp2 <- enquo(stamp2)

  name <- paste0(quo_name(stamp1), "_", quo_name(stamp2))

  df %>% 
    mutate(!!name := difftime(!!stamp1, !!stamp2, units=units))
}

Then you can do df %>% time_diff(time_2, time_1, "mins").

niko
  • 5,253
  • 1
  • 12
  • 32