RoyalTS RoyalTS - 2 months ago 20
R Question

Changing time zone on all timestamps using mutate_if and force_tz

I'm pulling data from a Postgres DB using the

RPostgreSQL
, which casts timestamps to the system time zone on import into R. So, after import I would like to set the time zone of all timestamps to UTC. I thought I would be able to elegantly do this using
dplyr
and
lubridate
, like so:

df %>%
mutate_if(lubridate::is.POSIXct, lubridate::force_tz(., tzone='UTC')) -> df


But this throws

Error in UseMethod("as.fun_list") :
no applicable method for 'as.fun_list' applied to an object of class "data.frame"


so I'm obviously using
mutate_if()
incorrectly

Answer

To use the dot notation in mutate_if, the function must be wrapped in funs.

library(lubridate)

df %>%
    mutate_if(is.POSIXct, funs(force_tz(., tzone='UTC')))

Currently, however, you cannot use the package:: notation within funs. Instead you would have to explicitly load the package as I did above (relevant github issue here).

Comments