合并列表的同一列表中的行
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
循环 list
和 rbind
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)
您想要二维 structure/array 还是简单地连接 a 和 b 列表中的值?如果是后者:
lapply(alllist, function(x) unname(unlist(x)))
[[1]]
[1] 1 2 3 4 5 6
[[2]]
[1] 2 4 5 6
一种基于purrr::map
和dplyr::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
我有一个包含两个列表的列表,其中第一个包含三个元素,第二个包含两个元素。我想对同一列表中的元素进行行组合。以下是一些数据:
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
循环 list
和 rbind
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)
您想要二维 structure/array 还是简单地连接 a 和 b 列表中的值?如果是后者:
lapply(alllist, function(x) unname(unlist(x)))
[[1]]
[1] 1 2 3 4 5 6
[[2]]
[1] 2 4 5 6
一种基于purrr::map
和dplyr::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