R语言中向POSIXct函数的tz参数传入字符串向量问题
Hey there! I totally get the frustration here—trying to map a vector of GMT timestamps to their unique corresponding timezones doesn't work with straightforward POSIXct() or with_tz() calls because those functions are designed to accept a single timezone string, not a vector of them. Let's fix this with element-wise processing.
Why Your Initial Attempts Failed
First, a quick clarification: Both POSIXct(tz = ...) and lubridate::with_tz(tz = ...) expect a single timezone value (like "America/New_York"). When you pass a vector of timezones, they'll either ignore all but the first value or throw a warning—they can't natively map each timestamp to its own timezone.
Solution 1: Base R with mapply()
If you prefer sticking to base R, mapply() is perfect for pairing elements from your two vectors and processing them one by one:
# Example sample data (replace with your actual vectors) GMTDteTmeStamp <- as.POSIXct(c("2024-05-20 12:00:00", "2024-05-20 13:00:00"), tz = "GMT") TZ <- c("America/New_York", "Europe/London") # Use mapply to convert each timestamp with its matching timezone local_time_list <- mapply( function(gmt_ts, tz) lubridate::with_tz(gmt_ts, tz = tz), GMTDteTmeStamp, TZ, SIMPLIFY = FALSE ) # Convert the resulting list to a POSIXct vector if needed local_time_vec <- do.call(c, local_time_list) # Check the output local_time_vec #> [1] "2024-05-20 08:00:00 EDT" "2024-05-20 14:00:00 BST"
Solution 2: Tidyverse with purrr::map2()
If you're working with a data frame (which is common for paired data), the tidyverse approach is clean and readable:
library(tidyverse) library(lubridate) # Example data frame (replace with your data) time_data <- tibble( GMTDteTmeStamp = as.POSIXct(c("2024-05-20 12:00:00", "2024-05-20 13:00:00"), tz = "GMT"), TZ = c("America/New_York", "Europe/London") ) # Add a column of converted local times time_data <- time_data %>% mutate(local_time = map2(GMTDteTmeStamp, TZ, ~with_tz(.x, tz = .y))) %>% unnest(local_time) # View the result time_data #> # A tibble: 2 × 3 #> GMTDteTmeStamp TZ local_time #> <dttm> <chr> <dttm> #> 1 2024-05-20 12:00:00 America/New_York 2024-05-20 08:00:00 #> 2 2024-05-20 13:00:00 Europe/London 2024-05-20 14:00:00
Key Notes
- Both methods handle daylight saving time automatically, so you don't need to adjust for that manually.
- Make sure your
TZvector uses valid timezone names (like those fromOlsonNames()—you mentioned manual single-timezone calls work, so your values are already good here).
内容的提问来源于stack exchange,提问作者Michael Byars

