簡體   English   中英

在列表列表的子集中組合向量

[英]Combining vectors in a subset of list of lists

我想獲得一個矩陣mat在名單列表的子集合並向量出來。 使用for循環執行以下操作。 我想知道是否有更快的方法。

  i <- 1 # the subset
  mat<- matrix(NA, ncol = p, nrow = n)
  for (j in 1 : p) {
    mat[, j] <- list_of_list[[j]][[i]]$the_vector
  }

編輯:我在任何給定時間由“ i”索引/子集的向量之后。 同樣, list_of_list也具有除the_vector以外的對象。

編輯2:在下面添加一個工作示例。

lst <- list()
list_of_list <- list()

lst[[1]] <- list(a="a", c="b1", the_vector = 1:5)
lst[[2]] <- list(a="b", c="b2", the_vector = 1:5+1)
lst[[3]] <- list(a="c", c="b3", the_vector = 1:5+2)
list_of_list[[1]] <- lst

lst[[1]] <- list(a="a", c="b1", the_vector = 1:5*0)
lst[[2]] <- list(a="b", c="b2", the_vector = 1:5*1)
lst[[3]] <- list(a="c", c="b3", the_vector = 1:5*22)
list_of_list[[2]] <- lst

i <- 1 # the subset
p <- 2 # length of the list of list
n <- 5 # length of the vector
mat<- matrix(NA, ncol = p, nrow = n)
for (j in 1 : p) {
  mat[, j] <- list_of_list[[j]][[i]]$the_vector
}

你可以unlist您的名單,然后重新塑造它作為一個matrix

matrix(unlist(list(list(1,2,3,4),list(5,6,7,8),list(9,10,11,12))), nrow=3, byrow = T)
     [,1] [,2] [,3] [,4]
[1,]    1    2    3    4
[2,]    5    6    7    8
[3,]    9   10   11   12

您可以嘗試sapply()函數:

i <- 1L
mat <- sapply(list_of_list, function(.x) .x[[i]]$the_vector)
mat
  [,1] [,2] [1,] 1 0 [2,] 2 0 [3,] 3 0 [4,] 4 0 [5,] 5 0 

我沒有對代碼進行基准測試,以確保這在執行速度方面更快,但是它肯定需要更少的按鍵。

sapply()在一個列表或向量應用一個函數,並且是種暗示for循環。

我不確定您是否正在尋找這樣的東西。 它將為您提供3個矩陣的列表,這些列表與list_of_list的子列表中的vector相對應。

mapply(list_of_list[[1]],list_of_list[[2]],
FUN = function(x,y){t(mapply(x$the_vector,y$the_vector,
FUN = function(u,v){matrix(c(u,v),ncol=2,byrow = F,dimnames = NULL)},
SIMPLIFY = T))},SIMPLIFY = F)


#[[1]]
#     [,1] [,2]
#[1,]    1    0
#[2,]    2    0
#[3,]    3    0
#[4,]    4    0
#[5,]    5    0

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

#[[3]]
#     [,1] [,2]
#[1,]    3   22
#[2,]    4   44
#[3,]    5   66
#[4,]    6   88
#[5,]    7  110

這是另一個確實類似於@TUSHAr的解決方案,但可能更具模塊化:

## Lapply wrapping function that outputs a matrix
lapply.wrapper <- function(i, list_of_list) {
    matrix(unlist(lapply(list_of_list, function(X, i) X[[i]]$the_vector, i = i)), ncol = length(list_of_list))
}

## Using the wrapper on the first subset:
lapply.wrapper(1, list_of_list)

#     [,1] [,2]
#[1,]    1    0
#[2,]    2    0
#[3,]    3    0
#[4,]    4    0
#[5,]    5    0

## Applying the function to all subsets
sapply(1:length(list_of_list[[1]]), lapply.wrapper, list_of_list, simplify = FALSE)

#[[1]]
#     [,1] [,2]
#[1,]    1    0
#[2,]    2    0
#[3,]    3    0
#[4,]    4    0
#[5,]    5    0
#
#[[2]]
#     [,1] [,2]
#[1,]    2    1
#[2,]    3    2
#[3,]    4    3
#[4,]    5    4
#[5,]    6    5
#
#[[3]]
#     [,1] [,2]
#[1,]    3   22
#[2,]    4   44
#[3,]    5   66
#[4,]    6   88
#[5,]    7  110

暫無
暫無

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

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