Benilton Carvalho
2012-Mar-09 15:12 UTC
[R] extracting the i-th row of a matrix in a list of lists
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
cberry at tajo.ucsd.edu
2012-Mar-09 17:15 UTC
[R] extracting the i-th row of a matrix in a list of lists
Benilton Carvalho <beniltoncarvalho at gmail.com> writes:> 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) >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> or should I really stick with: > > lapply(lapply(x1, '[[', 3), function(x) x[2,]) > > ? > > Thank you very much, > benilton >-- Charles C. Berry Dept of Family/Preventive Medicine cberry at ucsd edu UC San Diego http://famprevmed.ucsd.edu/faculty/cberry/ La Jolla, San Diego 92093-0901