在R中合并匹配列表中不同长度的元素
You can solve this by using mapply() with a custom function that adds the two columns to each data frame. R automatically recycles scalar values to match the number of rows in the data frame, so you don't need to manually repeat the color/value strings.
Base R Approach
First, define a helper function that takes a data frame and the corresponding info vector, then adds the new columns:
# Define the helper function add_metadata_cols <- function(df, metadata) { # Add color column (recycles the first element to all rows) df$color <- metadata[1] # Add value column (recycles the second element to all rows) df$value <- metadata[2] # Return the modified data frame df } # Apply the function to each pair of elements from your two lists new_combined_list <- mapply(add_metadata_cols, first_list, second_list, SIMPLIFY = FALSE)
Tidyverse Alternative (using purrr and dplyr)
If you prefer working with the tidyverse, map2() from purrr paired with mutate() from dplyr is a clean way to do this:
library(purrr) library(dplyr) new_combined_list <- map2(first_list, second_list, ~ { .x %>% mutate( color = .y[1], value = .y[2] ) })
How this works
- Both
mapply()andmap2()iterate over your two lists in parallel, so each data frame from the first list is paired with the corresponding vector from the second list. - When you assign a single value (like
"green") to a new column in a data frame, R automatically repeats that value to match the number of rows in the data frame—this is called vector recycling, and it's exactly what you need here.
Testing this with your sample data will produce the exact structure you described: each data frame in the new list will have the original x, y, layer columns plus the new color and value columns with repeated values.
内容的提问来源于stack exchange,提问作者Cameron

