Skip to content

extracting the i-th row of a matrix in a list of lists

3 messages · Benilton Carvalho, Charles C. Berry

#
Hi,

what is the proper of of "passing a missing value" so I can extract
the entire i-th row of a matrix (in a list of lists) without
pre-computing the number of cols?

For example, if I know that the matrices have 2 columns, I can do the following:

set.seed(1)
x0 <- lapply(1:10, function(i) replicate(4, list(matrix(rnorm(10), nc=2))))
lapply(lapply(x0, '[[', 3), '[', i=2, j=1:2)

(given that if I don't specify j, I only get the first element)

but if the number of columns are variable:

x1 <- lapply(1:10, function(i) replicate(4, list(matrix(rnorm(100),
nc=sample(c(2, 4, 5, 10), 1)))))

what would be the value of J below?

lapply(lapply(x1, '[[', 3), '[', i=2, j=J)

or should I really stick with:

lapply(lapply(x1, '[[', 3), function(x) x[2,])

?

Thank you very much,
benilton
#
Benilton Carvalho <beniltoncarvalho at gmail.com> writes:
I think you want 'j=TRUE'. Note:

all.equal( 
         lapply(lapply(x0, '[[', 3), '[', i=2,j=TRUE),
         lapply(lapply(x0, '[[', 3), '[', i=2, j=1:2)
         )

HTH,

Chuck

  
    
#
Hi Chuck, thank you *very* much! That really helped! b
On 9 March 2012 17:15, <cberry at tajo.ucsd.edu> wrote: