0

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

1 Answer 1

2

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
Sign up to request clarification or add additional context in comments.

1 Comment

Indeed, I think the problem is that tz argument is not being vectorized, but I don't know why. Anyway, your solution works perfectly. Thank you.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.