Robert's Data Science Blog

Rename with across

library(dplyr)

Consider a tibble:

tbl <- tibble::tibble(
    Timestamp1UTC = as.POSIXct("2020-02-29 12:34:56", tz = "UTC"),
    Timestamp2UTC = as.POSIXct("2020-02-29 01:23:45", tz = "UTC"),
)
tbl
## # A tibble: 1 x 2
##   Timestamp1UTC       Timestamp2UTC      
##   <dttm>              <dttm>             
## 1 2020-02-29 12:34:56 2020-02-29 01:23:45

I want to get two new columns with the time stamps in the CET timezone. With the mutate_at/mutate_if functions from dplyr we can modify multiple columns, but the across function in dplyr 1.0 provide a way to save the results as new columns. (I only include one column to fit the page)

tbl %>% 
    select(Timestamp1UTC) %>% 
    mutate(
        across(
            ends_with("UTC"), 
            lubridate::with_tz, tzone = "CET", 
            .names = "{sub('UTC', 'CET', col)}"
        )
    )
## # A tibble: 1 x 2
##   Timestamp1UTC       Timestamp1CET      
##   <dttm>              <dttm>             
## 1 2020-02-29 12:34:56 2020-02-29 13:34:56

The .names argument use the syntax from the glue package where col is the name of the column.