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

在R语言中按名称合并列表的多个子列表

Hey there! Let's tackle this problem. You want to merge all your sublists by their named elements (a, b, c, etc.)—so all the a vectors from sublists 1 to 50 get concatenated into one big a vector, same for b and c.

Here are two straightforward approaches, using base R and the tidyverse's purrr package, which work seamlessly even for 40-50 sublists:

Base R Solution

You can use do.call() to pass all your sublists as arguments to mapply(), which will handle element-wise concatenation automatically:

# First, let's create a sample list with 50 sublists (mimicking your structure)
set.seed(123) # For reproducible random values
l <- lapply(1:50, function(i) {
  list(
    a = sample(1:100, 3),
    b = sample(1:100, 3),
    c = sample(1:100, 3)
  )
})
names(l) <- as.character(1:50) # Name sublists "1" to "50"

# Merge by named elements
l2 <- do.call(mapply, c(FUN = c, l, SIMPLIFY = FALSE))

How this works:

  • do.call(mapply, ...) takes every sublist in l and feeds them as individual arguments to mapply().
  • FUN = c tells mapply() to concatenate all matching named elements (e.g., all a vectors from sublists 1-50, all b vectors, etc.).
  • SIMPLIFY = FALSE ensures the result stays a list (instead of coercing to a matrix if possible), which matches your desired structure.

Tidyverse (purrr) Solution

If you prefer tidyverse syntax, purrr::transpose() is perfect here—it rearranges your list to group by element names instead of sublist numbers. Then you just concatenate each group:

library(purrr)

# Using the same sample list l from above
l2 <- map(transpose(l), c)

How this works:

  • transpose(l) flips the list structure: instead of list("1" = list(a, b, c), "2" = list(a, b, c), ...), you get list(a = list(a1, a2, ..., a50), b = list(b1, b2, ..., b50), c = list(c1, c2, ..., c50)).
  • map(..., c) applies the concatenation function c to each element in the transposed list, turning each list of small vectors into a single combined vector.

Both methods will give you exactly the structure you need—l2 will have a, b, c elements, each being the concatenation of all corresponding vectors from your 40-50 sublists.

内容的提问来源于stack exchange,提问作者PK1998

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.05.09 20:37:42