0

I want to extract one matrix of a list of matrices. However, this extracted matrix should not be a list anymore. Probably it is very easy to do this, but I can not find the solution. Here some example data:

x = list(a = matrix(sample(1:5,4) , nrow=2, ncol=2),
         b = matrix(sample(5:10,4) , nrow=2, ncol=2),
         c = matrix(sample(10:15,4) , nrow=2, ncol=2))  

I selected one of the matrices by name (which is important in my case, as I have more than 1000 matrices), but it is still a list of one item:

new <- x["b"]

I tried as.matrix(new) which returns something different. And also lapply(new, function(r){r["b"]}). My question: how to extract one matrix, with str()=matrix and not list? Thanks

Josh O'Brien
  • 159,210
  • 26
  • 366
  • 455
N.Varela
  • 910
  • 1
  • 11
  • 25

2 Answers2

1

You could use x[['b']] or x$b

x = list(a = matrix(sample(1:5,4) , nrow=2, ncol=2),
         b = matrix(sample(5:10,4) , nrow=2, ncol=2),
         c = matrix(sample(10:15,4) , nrow=2, ncol=2))  

x[['b']]
     [,1] [,2]
[1,]    6   10
[2,]    9    7

x$b
     [,1] [,2]
[1,]    6   10
[2,]    9    7

Here is the microbenchmark between the 2 solutions :

microbenchmark(x[['b']],x$b)
Unit: nanoseconds
     expr min  lq   mean median   uq   max neval cld
 x[["b"]] 351 701 756.80    701  701  3851   100   a
      x$b 700 701 942.33    701 1050 15400   100   a
etienne
  • 3,648
  • 4
  • 23
  • 37
1

There are two common subsetting operations ?"[" and ?"[[" in R. The difference between them is that [ returns the subset in the same type as the "parent" object, in your case a list, while [[ returns the object in type of the subset object.

So:

l <- list(v= 1:10, # a vector
          m= matrix(1:4, 2,2), # a matrix
          l2= list(a= c("a", "b", "c"), b= c("d", "e", "f")))

l[1] # all of these will return
l[2] # a list of length one
l[3] # containing the object in the list "l"

l[[1]] # will return a vector
l[[2]] # will return a matrix
l[[3]] # will return a list

If you have a named list (as l is above) subsetting via the name (eg l$v) will return the base object similar to [[.

alexwhitworth
  • 4,839
  • 5
  • 32
  • 59