在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 inland feeds them as individual arguments tomapply().FUN = ctellsmapply()to concatenate all matching named elements (e.g., allavectors from sublists 1-50, allbvectors, etc.).SIMPLIFY = FALSEensures 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 oflist("1" = list(a, b, c), "2" = list(a, b, c), ...), you getlist(a = list(a1, a2, ..., a50), b = list(b1, b2, ..., b50), c = list(c1, c2, ..., c50)).map(..., c)applies the concatenation functioncto 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

