[R] Can a matrix have 'list' as rows/columns?

Patrick Burns pburns at pburns.seanet.com
Tue Apr 17 11:04:05 CEST 2012


That is a fine section of 'The R Inferno'
but I don't think it applies to your problem.

The answer to your question in the subject line
is obviously "yes".  It happens when the matrix
(or more generally any array) is of mode "list".

A useful example of this is in Circle 8.1.8.

http://www.burns-stat.com/pages/Tutor/R_inferno.pdf

In your case you can do things like:

 > M[[1,1]]
[1] "aaa"
 > M[[1,2]]
[1] "bbb"
 > M[[2,2]]
[1] 0.274498

But not:

 > M[[,2]]
Error in M[[, 2]] : invalid subscript type 'symbol'


Pat

On 17/04/2012 05:13, Worik R wrote:
> After a lot of processing I get a matrix into M.  I expected each row and
> column to be a vector.  But it is a list.
>
> R-Inferno says...
>
> "Arrays (including matrices) can be subscripted with a matrix of positive
> numbers. The subscripting matrix has as many columns as there are dimensions
> in the array—so two columns for a matrix. The result is a vector (not an
> array)
> containing the selected items."
>
> My version of R:
> version.string R version 2.12.1 (2010-12-16)
>
> Here is an example...
>
>> Qm<- c("aaa", "bbb", "ccc")
>> DF<- data.frame(Name=sample(Qm, replace=TRUE, size=22), Value=runif(22),
> stringsAsFactors=FALSE)
>> M<- sapply(Qm, function(nm, DF){last(DF[DF[, "Name"]==nm,])}, DF)
>> class(M)
> [1] "matrix"
>> class(M[,1])
> [1] "list"
>> class(M[1,])
> [1] "list"
>> M
>        aaa       bbb      ccc
> Name  "aaa"     "bbb"    "ccc"
> Value 0.4702648 0.274498 0.5529691
>> DF
>     Name      Value
> 1   ccc 0.99948920
> 2   aaa 0.51921281
> 3   aaa 0.10803943
> 4   aaa 0.82265847
> 5   ccc 0.83237260
> 6   bbb 0.88250933
> 7   aaa 0.41836131
> 8   aaa 0.66197290
> 9   ccc 0.01911771
> 10  ccc 0.99994699
> 11  bbb 0.35719884
> 12  ccc 0.86274858
> 13  bbb 0.57528579
> 14  aaa 0.12452158
> 15  aaa 0.44167731
> 16  aaa 0.11660019
> 17  ccc 0.55296911
> 18  aaa 0.12796890
> 19  bbb 0.44595741
> 20  bbb 0.93024768
> 21  aaa 0.47026475
> 22  bbb 0.27449801
>>
>
> 	[[alternative HTML version deleted]]
>
>
>
>
> ______________________________________________
> 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.

-- 
Patrick Burns
pburns at pburns.seanet.com
twitter: @portfolioprobe
http://www.portfolioprobe.com/blog
http://www.burns-stat.com
(home of 'Some hints for the R beginner'
and 'The R Inferno')



More information about the R-help mailing list