[R] creating matrices from lists

David Winsemius dwinsemius at comcast.net
Tue Sep 21 04:48:17 CEST 2010


On Sep 20, 2010, at 10:28 PM, David Winsemius wrote:

>
> On Sep 20, 2010, at 10:12 PM, Gregory Ryslik wrote:
>
>> Hi,
>>
>> I have a list of 5 main elements where each main element has 247  
>> atomic entries either 0 or 1. I need to get this into a 247x5  
>> matrix so I do "do.call(cbind, mylist)".  However, it renumbers 0  
>> to a 1 and the 1 to a 2 so that my matrix is filled with 1's and 2's.
>>
>
> If I had such a problem I would see if this were more effective:
>
> matrix(unlist(mylist), length(mylist[[1]]) )
>
> (There is the column major order default of R matrices.)
>
>> I understand I can fix it in this case by doing a replace but I  
>> would like to avoid that step. Further, sometimes, my list entries  
>> will be from 0 to n. I don't want to have to always renumber all  
>> the possibilities.
>>
>> I'm not quite sure why this is going on because when I build the  
>> following: l <- list(c(1,2,3),c(1,2,3),c(1,2,3))
>> and execute do.call(cbind, l) it works just fine and there is no  
>> renumbering!
>
> I wouldn't have expected it either, but you only provided an example  
> of what did work. My attempt at reproducing your problem also failed:
>
> > ll <- list(a=c(1,0,1,1,0), b=c(0,1,0,0,1)  )
> > do.call(cbind, ll)
>     a b
> [1,] 1 0
> [2,] 0 1
> [3,] 1 0
> [4,] 1 0
> [5,] 0 1
>
> I am wondering if you are dealing with factors and have not looked  
> at your "list" with str(). Haven't tried my method above to see what  
> would happen in tat instance.

Does seem possible that is the issue:
 > do.call(cbind,  
list(factor(c(0,1,0,1,1,1,0)),b=factor(c(0,0,0,1,1,1,1))))
        b
[1,] 1 1
[2,] 2 1
[3,] 1 1
[4,] 2 2
[5,] 2 2
[6,] 2 2
[7,] 1 2

-- 
David.



More information about the R-help mailing list