[R] matrix from list

Greg Snow Greg.Snow at imail.org
Fri Apr 25 17:07:30 CEST 2008


You may want to read the help page for '[' and '[[' a few more times
(the differencese can be subtle).

The '[[' only returns a single element from a data structure (but in the
case of a list, that single element can be quite complex).  So something
like list[[1:2]] does not make sense because you are asking something
that returns 1 thing to return 2.  You can do list[1:2] which will
return a list consisting of the 1st 2 elements of the original list.  If
you list happens to be a data frame as well, then you can subset it like
a matrix: mydf[1:2, 3:4] gives the 1st 2 rows of columns 3 and 4,
mydf[,1:2] gives the first 2 columns.  These will continue to be data
frames (since '[' returns the same type of object), but tools like
as.matrix can convert this into a matrix.

-- 
Gregory (Greg) L. Snow Ph.D.
Statistical Data Center
Intermountain Healthcare
greg.snow at imail.org
(801) 408-8111
 
 

> -----Original Message-----
> From: r-help-bounces at r-project.org 
> [mailto:r-help-bounces at r-project.org] On Behalf Of Olivier Lefevre
> Sent: Thursday, April 24, 2008 4:16 PM
> To: r-help at stat.math.ethz.ch
> Subject: Re: [R] matrix from list
> 
> Yes, unlist is the magic wand I was looking for. Thanks a million!
> 
> Having said that, I find it rather arbitrary that you can 
> write mat[1:4] but not list[[1:2]]; IMO there should be no 
> need for a "magic" operator like unlist: 
> list[[1:length(list)]] could do the job.
> 
> -- O.L.
> 
> ______________________________________________
> 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