You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

在R中合并匹配列表中不同长度的元素

Solution

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() and map2() 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

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.08.04 17:40:18