lubridate icon indicating copy to clipboard operation
lubridate copied to clipboard

with_tz in if_else not working

Open dominicroye opened this issue 4 years ago • 1 comments

I have problems with the use of with_tz() in if_else() with mutate(). I wanted to change the time zone according to a variable, but it doesn't work as I expected. The similar question raised some time ago at StackOverflow: https://stackoverflow.com/questions/57765186/using-dplyrif-else-in-r-to-change-the-time-zone-of-posixct-timestamps-based

I don't know if it is related to dplyr or lubridate. Any ideas on the reason?

library(tidyverse)
library(lubridate)

df <- tibble(var = c("Madrid", "London", "London"),
             datetime = ymd_hm(c("2005-05-08 16:00", 
                                 "2006-08-09 10:00", 
                                 "2008-04-30 22:00")))

mutate(df, datetime2 = if_else(var == "London",
                              datetime %>% with_tz("Europe/London"),
                              datetime %>% with_tz("Europe/Madrid")))

# as vector it is working 
ymd_hm("2005-05-08 16:00") %>% with_tz("Europe/Madrid")
ymd_hm("2005-08-09 10:00") %>% with_tz("Europe/London")

dominicroye avatar Feb 17 '21 16:02 dominicroye

date time vectors in R can have only one time zone. What happens in your case is that the datetime2 is having london tz.

> mutate(df,
+        london = datetime %>% with_tz("Europe/London"),
+        madrid = datetime %>% with_tz("Europe/Madrid"),
+        datetime2 = if_else(var == "London",
+                            datetime %>% with_tz("Europe/London"),
+                            datetime %>% with_tz("Europe/Madrid")))
# A tibble: 3 x 5
  var    datetime            london              madrid              datetime2          
  <chr>  <dttm>              <dttm>              <dttm>              <dttm>             
1 Madrid 2005-05-08 16:00:00 2005-05-08 17:00:00 2005-05-08 18:00:00 2005-05-08 17:00:00
2 London 2006-08-09 10:00:00 2006-08-09 11:00:00 2006-08-09 12:00:00 2006-08-09 11:00:00
3 London 2008-04-30 22:00:00 2008-04-30 23:00:00 2008-05-01 00:00:00 2008-04-30 23:00:00
> 

It's not clear to me what you want to achieve. If you tell us the desired output we might help. For now, my feeling is that you want force_tz instead.

> mutate(df,
+        london = datetime %>% with_tz("Europe/London"),
+        datetime2 = if_else(var == "London",
+                            datetime %>% force_tz("Europe/London"),
+                            datetime %>% force_tz("Europe/Madrid")))
# A tibble: 3 x 4
  var    datetime            london              datetime2          
  <chr>  <dttm>              <dttm>              <dttm>             
1 Madrid 2005-05-08 16:00:00 2005-05-08 17:00:00 2005-05-08 15:00:00
2 London 2006-08-09 10:00:00 2006-08-09 11:00:00 2006-08-09 10:00:00
3 London 2008-04-30 22:00:00 2008-04-30 23:00:00 2008-04-30 22:00:00

vspinu avatar Feb 17 '21 22:02 vspinu