RoyalTS RoyalTS - 1 year ago 67
R Question

Changing time zone on all timestamps using mutate_if and force_tz

I'm pulling data from a Postgres DB using the

, 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
, 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

Answer Source

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


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).