如何处理多DataFrame:合并指定列、删除原列及转换POSIXct格式?
1. Binding Two Columns from Multiple DataFrames in a List
Suppose you have a list of DataFrames (let’s call it df_list) and want to pull two specific columns (say date_col and time_col) from each, then combine them into a single DataFrame. Here are two practical approaches using base R and the tidyverse:
Base R Method
# Extract the target columns from each DataFrame in the list extracted_cols <- lapply(df_list, function(df) df[, c("date_col", "time_col")]) # Bind all extracted columns into one DataFrame combined_df <- do.call(rbind, extracted_cols)
Tidyverse (purrr) Method
If you prefer a more concise syntax, map_dfr handles the extraction and binding in one line:
library(purrr) combined_df <- map_dfr(df_list, ~ .x[, c("date_col", "time_col")])
This automatically stacks the results row-wise into a single DataFrame.
2. Merging Columns, Dropping Originals, and Converting to POSIXct
Let’s say you have multiple DataFrames loaded in your global environment (e.g., df1, df2, df3). For each, you want to merge date_col and time_col into a datetime column, remove the original two columns, and convert the new column to POSIXct type.
First, get the names of your target DataFrames. If they follow a naming pattern (like starting with "df"), use:
df_names <- ls(pattern = "^df") # Adjust the pattern to match your DataFrame names
Then, loop through each DataFrame to make the changes:
# Base R approach for (name in df_names) { df <- get(name) # Combine date and time (adjust the format string to match your data) df$datetime <- as.POSIXct(paste(df$date_col, df$time_col), format = "%Y-%m-%d %H:%M:%S") # Drop original columns df <- df[, !names(df) %in% c("date_col", "time_col")] # Update the DataFrame in your environment assign(name, df) } # Tidyverse (dplyr) approach for cleaner code library(dplyr) for (name in df_names) { df <- get(name) %>% mutate(datetime = as.POSIXct(paste(date_col, time_col), format = "%Y-%m-%d %H:%M:%S")) %>% select(-date_col, -time_col) assign(name, df) }
Important: Double-check that the format argument matches the actual structure of your date/time strings (e.g., "%m/%d/%Y" for month/day/year formats).
内容的提问来源于stack exchange,提问作者Antonio Bonilla

