如何将数据框的奇数列转换为POSIXct格式?
Let’s break down why your current approaches are failing and fix this step by step:
- Running
as.POSIXct(timestamptest2[, odd_indexes])directly throws an error becauseas.POSIXct.defaultdoesn’t know how to process a data frame input—it expects a single vector, not multiple columns at once. - Using
apply()converts your data frame columns into a matrix, which often coerces factor columns to their underlying integer codes instead of keeping the date string values. That’s why you get the "character string is not in a standard unambiguous format" error—you’re accidentally trying to convert integers, not actual date strings.
Here are two reliable, tested solutions:
1. Base R Approach with lapply()
lapply() processes each column individually without coercing to a matrix, preserving the original column structure. We’ll also handle factor columns (a common hidden issue here) by converting them to characters first:
# Define your odd column indexes (example: c(1,3,5) for a 5-column data frame) odd_indexes <- seq(1, ncol(timestamptest2), by = 2) # Convert target columns to POSIXct timestamptest2[, odd_indexes] <- lapply(timestamptest2[, odd_indexes], function(col) { # Convert factors to character strings if needed if (is.factor(col)) { col <- as.character(col) } # Specify timezone to match your expected output (CEST maps to "Europe/Berlin") as.POSIXct(col, tz = "Europe/Berlin") })
2. Tidyverse Approach with dplyr::mutate_at()
If you use the tidyverse ecosystem, this syntax is cleaner and more readable:
library(dplyr) odd_indexes <- seq(1, ncol(timestamptest2), by = 2) timestamptest2 <- timestamptest2 %>% mutate_at(vars(odd_indexes), ~as.POSIXct(., tz = "Europe/Berlin"))
Bonus: Handle Non-Standard Date Formats
If your date strings don’t follow R’s default expected format, add the format parameter to as.POSIXct(). For example, if your dates look like 01-05-2018 15:00:16, use:
as.POSIXct(col, tz = "Europe/Berlin", format = "%d-%m-%Y %H:%M:%S")
Verify the Fix
Check the column types after conversion to confirm success:
str(timestamptest2[, odd_indexes])
You should see each column listed as POSIXct with the correct timezone attached.
内容的提问来源于stack exchange,提问作者tfkLSTM

