簡體   English   中英

合並列表的同一列表中的行

[英]Combine rows within the same list of a list

我有一個包含兩個列表的列表,其中第一個包含三個元素,第二個包含兩個元素。 我想將同一列表中的元素組合起來。 以下是一些數據:

list1 <- list(a = c(1,2,3), b = c(4,5,6)) #the first nested list which has three elements
list2 <- list(a = c(2,4), b = c(5,6)) #the second nested list which has two elements
alllist<- list(list1, list2) #the combo list that nests list1 and list2

最后,我簡單地將alllist轉換為如下所示的列表:

[[1]]
[1] 1 2 3
[1] 4 5 6

[[2]]
[1] 2 4
[1] 5 6

一種purrr::mapdplyr::bind_rows的方法,其靈感來自@akrun 第一個解決方案:

library(tidyverse)

alllist %>% map(~ bind_rows(.x) %>% unname %>% t) 

#> [[1]]
#>      [,1] [,2] [,3]
#> [1,]    1    2    3
#> [2,]    4    5    6
#> 
#> [[2]]
#>      [,1] [,2]
#> [1,]    2    4
#> [2,]    5    6

循環listrbind

lapply(alllist, \(x) do.call(rbind, unname(x)))

-輸出

[[1]]
     [,1] [,2] [,3]
[1,]    1    2    3
[2,]    4    5    6

[[2]]
     [,1] [,2]
[1,]    2    4
[2,]    5    6

或者可以使用simplify2array

lapply(alllist, simplify2array)

你想要一個二維結構/數組還是簡單地連接 a 和 b 列表中的值? 如果是后者:

lapply(alllist, function(x) unname(unlist(x)))

[[1]]
[1] 1 2 3 4 5 6

[[2]]
[1] 2 4 5 6

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM