5

我有一个包含 100 个元素的列表。每个元素都是一个列表。这个列表中有两个元素。一个只是键,另一个是矩阵。这个矩阵有 5 列。我正在尝试从每个矩阵中为所有元素提取一列。所以基本上我会再次将 100 个矩阵作为列表的一个元素。这是列表的样子

a[[1]]
     [[1]]
          [1] "keyid"

      [[2]] 
              [,1]                [,2]          [,3]    [,4]    [,5]
          [1,] "1329397986.572332" "x" "y" "z" "a"
          [2,] "1329242747.368294" "x" "y" "z" "a"
          [3,] "1329194224.351232 "x" "y" "z" "a"

所以你在这里看到的是一个列表,它有 100 个元素。每个元素都是 2 个元素的列表。我目前只对第二个元素感兴趣。第二个元素有一个矩阵。我想提取这个矩阵的第一列。只是想看看我是否可以将列提取到我可以做的向量中

a[[1]][[2]][,1] 

我将所有值作为向量获取,如下所示。

a[[1]][[2]][,1]  
       [1] "1329397986.572332" "1329242747.368294" "1329194224.351232" 

但是当我这样做时

 x <- lapply(a,function(r){r[[2]][,1]})

以下是我得到的错误。

> x <- lapply(a, function(r){r[[2]][,1]})
Error in r[[2]][, 1] : incorrect number of dimensions

我不确定我为什么会这样。我检查了矩阵元素的尺寸。

> dim(a[[1]][[2]])
  [1] 52  5

它看起来是正确的。所以我不确定错误在哪里。

dput(a) 给出

dput(a)
[[1]]
[[1]][[1]]
[1] "keyid"

[[1]][[2]]
  [,1]                [,2]          [,3]    [,4]    [,5]
[1,] "1329397986.572332" "x"   "y"     "z"     "a"
[2,] "1329242747.368294" "x"   "y"     "z"     "a"
[3,] "1329194224.351232" "x"   "y"     "z"     "a"

[[2]]
[[2]][[1]]
[1] "keyid"

[[2]][[2]]
  [,1]                [,2]          [,3]    [,4]    [,5]
[1,] "1329397986.572332" "x"   "y"     "z"     "a"
[2,] "1329242747.368294" "x"   "y"     "z"     "a"
[3,] "1329194224.351232" "x"   "y"     "z"     "a"

...

[[100]]
[[100]][[1]]
[1] "keyid"

[[100]][[2]]
  [,1]                [,2]          [,3]    [,4]    [,5]
[1,] "1329397986.572332" "x"   "y"     "z"     "a"
[2,] "1329242747.368294" "x"   "y"     "z"     "a"
[3,] "1329194224.351232" "x"   "y"     "z"     "a"
4

2 回答 2

11

对于很少使用的功能来说,这似乎是一个完美的案例rapply

在发布可重现的示例之前,我会将其发布为可能的解决方案

set.seed(1)
# a possible reproducible example
a <- replicate(5, list('a', matrix(runif(10), ncol=5)), simplify = FALSE)

# the first column
a1 <- rapply(a, classes = 'matrix', how = 'list', f = function(x) x[, 1, drop = FALSE]) 
# a second `lapply` is required to drop `NULL` entries

a1Only <- lapply(a1, Filter, f = Negate(is.null))
于 2013-04-24T02:26:15.993 回答
5

尝试这个:

a <- list(list("keyid", structure(c("1329397986.572332", "1329242747.368294", 
"1329194224.351232", "x", "x", "x", "y", "y", "y", "z", "z", 
"z", "a", "a", "a"), .Dim = c(3L, 5L))), list("keyid", structure(c("1329397986.572332", 
"1329242747.368294", "1329194224.351232", "x", "x", "x", "y", 
"y", "y", "z", "z", "z", "a", "a", "a"), .Dim = c(3L, 5L))))

sapply( lapply(a, "[[" , 2) , "[", TRUE, 1)
     [,1]                [,2]               
[1,] "1329397986.572332" "1329397986.572332"
[2,] "1329242747.368294" "1329242747.368294"
[3,] "1329194224.351232" "1329194224.351232"

解释:innerlapply拉出每个子列表中的第二个元素,将其传递给 external sapply。(外部)sapply用于[从传递给它的每个对象中提取第一列。由于[是一个原始函数,即仅使用位置参数的函数,因此您确实需要使用占位符,这是提供“TRUE”参数的目的。它的目的是将“1”“推”到第二个参数位置,从而使其成为列选择器而不是行选择器。

于 2013-04-24T04:20:00.293 回答