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

Benilton Carvalho beniltoncarvalho at gmail.com
Fri Mar 9 22:19:04 CET 2012


Hi Chuck, thank you *very* much! That really helped! b

On 9 March 2012 17:15,  <cberry at tajo.ucsd.edu> wrote:
> 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
>
> ______________________________________________
> R-help at r-project.org mailing list
> https://stat.ethz.ch/mailman/listinfo/r-help
> PLEASE do read the posting guide http://www.R-project.org/posting-guide.html
> and provide commented, minimal, self-contained, reproducible code.



More information about the R-help mailing list