giltrapo
giltrapo

Reputation: 83

Add new variable in data table using others variables like arguments in built in function

I'm trying to create a new variable in a data table with format function and I'm using two variables from the data table itself as arguments, but function doesn't recognize one of them. Why?

> dt <- data.table(date = as.POSIXct(c("2018-06-13 11:00:00", "2018-06-13 11:00:00")), time_zone = c("America/Lima", "America/Sao_Paulo"))
> dt
                  date         time_zone
1: 2018-06-13 11:00:00      America/Lima
2: 2018-06-13 11:00:00 America/Sao_Paulo

> dt[, localdate := format(as.POSIXct(date), tz = time_zone, usetz = TRUE)]
Error in as.POSIXlt.POSIXct(x, tz) : invalid 'tz' value

Upvotes: 0

Views: 37

Answers (1)

zack
zack

Reputation: 5415

I think the issue has to do with the tz argument not being vectorized (someone else may be able to put it more elegantly / accurately). Wrapping this all in an *apply can help enable this type of vectorization:

dt[, localdate := mapply(function(t, tz) format(as.POSIXct(t), tz = tz, usetz = TRUE), date, time_zone)]

dt
                  date         time_zone               localdate
1: 2018-06-13 11:00:00      America/Lima 2018-06-13 13:00:00 -05
2: 2018-06-13 11:00:00 America/Sao_Paulo 2018-06-13 15:00:00 -03

Upvotes: 2

Related Questions