Skip to content

Creating lists from matrices

5 messages · Alexander Sokol, Peter Dalgaard, Eric Lecoutre +2 more

#
Hello,

I am using R 1.9.1 on Windows 2000 SP4. I have the following problem:

Say I have a matrix,
[,1]   [,2]   [,3]
[1,]   "A"   "B"   "C"
[2,]   "D"   "E"   "F"
[3,]   "G"   "H"   "I"

I would like to apply an operation to this matrix which returns a list my.list 
containing the following 3 elements,
[[1]]
[1] "A" "B" "C"
[[2]]
[2] "D" "E" "F"
[[3]]
[3] "G" "H" "I"

That is, each row of the original matrix is turned into a vector and these 
vectors are collected to a list. How do I do this?

Thanks,
 Alexander
#
Alexander Sokol <alexandersokol at ofir.dk> writes:
split(my.matrix, row(my.matrix))
#
Hi,

One could use the following:

 >  mm=matrix(letters[1:9],ncol=3,byrow=TRUE)
 >  lapply(apply(mm,1,list),function(el)el[[1]])
[[1]]
[1] "a" "b" "c"

[[2]]
[1] "d" "e" "f"

[[3]]
[1] "g" "h" "i"

You could also have a look at as.data.frame.matrix, which transform a 
matrix into a data.frame efficiently. data.frames are internaly structured 
as lists...

Eric
At 10:12 25/11/2004, Alexander Sokol wrote:
Eric Lecoutre
UCL /  Institut de Statistique
Voie du Roman Pays, 20
1348 Louvain-la-Neuve
Belgium

tel: (+32)(0)10473050
lecoutre at stat.ucl.ac.be
http://www.stat.ucl.ac.be/ISpersonnel/lecoutre

If the statistics are boring, then you've got the wrong numbers. -Edward 
Tufte
#
Hi Alexander,

you could try this:

(my.matrix <- matrix(LETTERS[1:9], 3, byrow=TRUE))
split(my.matrix, row(my.matrix))


I hope it helps.

Best,
Dimitris

----
Dimitris Rizopoulos
Ph.D. Student
Biostatistical Centre
School of Public Health
Catholic University of Leuven

Address: Kapucijnenvoer 35, Leuven, Belgium
Tel: +32/16/336899
Fax: +32/16/337015
Web: http://www.med.kuleuven.ac.be/biostat
     http://www.student.kuleuven.ac.be/~m0390867/dimitris.htm


----- Original Message ----- 
From: "Alexander Sokol" <alexandersokol at ofir.dk>
To: <r-help at stat.math.ethz.ch>
Sent: Thursday, November 25, 2004 10:12 AM
Subject: [R] Creating lists from matrices
#
my.matrix <- matrix(LETTERS[1:9],3,3,byrow=TRUE)
split(my.matrix, row(my.matrix))

$"1"
[1] "A" "B" "C"

$"2"
[1] "D" "E" "F"

$"3"
[1] "G" "H" "I"

which even names the rows for you.
On Thu, 25 Nov 2004, Alexander Sokol wrote: