[R] how to collapse list into a matrix with names

Paul Hiemstra p.hiemstra at geo.uu.nl
Thu Nov 5 12:33:34 CET 2009


Hi Synny,

If you just want to write it to a file you can something like:

m_list = list(a = matrix(runif(100), 10, 10),
                    b = matrix(runif(100), 10, 10),
                    c = matrix(runif(100), 10, 10))

for (i in 1:3) {
  write(file = "dump.txt",names(m_list)[i],append=TRUE)
  write.table(file = "dump.txt",m_list[[i]],append=TRUE,
                      row.names = FALSE,
                      col.names = FALSE)
}

cheers,
Paul (& my colleague Jon)

Sunny Srivastava wrote:
> Dear R-Helpers,
> I have the following code:
>
> data =
>   read.csv("test.csv",header=T,na.strings="-",row.names=1)
> myData=as.matrix(data)
>
> ##myData is a 102x19 matrix
> myList = alply(myData, 2,function(x){matrix(x,ncol=6,byrow=T)})
>
> ##myList is a list containing 19 matrices with the following names
>   
>> names(myList)
>>     
>  [1] "*ES"       "*ET"       "*ER"       "*DS"       "*DT"       "*DR"
>  [7] "*VS"       "*VT"       "*G4per"    "*G29per"   "*FvFm42"   "*FvFm29"
> [13] "*Tillers"  "*DryWtGC"  "*LeafArea" "*SPAD"     "*RootCon"  "*ShootCon"
> [19] "*LeafTips"
>
> I want to save the result of the list into a file, so that the matrices are
> placed one below the other AND the name is also written above the
> corresponding matrix.
>
> Something like ..
>
> *ES
> 1st-matrix
> *ET
> 2nd-matrix
> ...
>
> *LeafTips
> 19th-matrix
>
>
> if I do -
>
> do.call("rbind",myList)
>
> It combines all these matrices but the names of these matrices are lost.
>
> Any ideas?
>
> Thanks
> S.
>
> sessionInfo()
> ---------------------
> R version 2.9.2 (2009-08-24)
> x86_64-pc-linux-gnu
>
> locale:
> LC_CTYPE=en_US.UTF-8;LC_NUMERIC=C;LC_TIME=en_US.UTF-8;LC_COLLATE=en_US.UTF-8;LC_MONETARY=C;LC_MESSAGES=en_US.UTF-8;LC_PAPER=en_US.UTF-8;LC_NAME=C;LC_ADDRESS=C;LC_TELEPHONE=C;LC_MEASUREMENT=en_US.UTF-8;LC_IDENTIFICATION=C
>
> attached base packages:
> [1] stats     graphics  grDevices utils     datasets  methods   base
>
> other attached packages:
> [1] plyr_0.1.9
> ------------------------
>
> 	[[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.
>   


-- 
Drs. Paul Hiemstra
Department of Physical Geography
Faculty of Geosciences
University of Utrecht
Heidelberglaan 2
P.O. Box 80.115
3508 TC Utrecht
Phone:  +3130 274 3113 Mon-Tue
Phone:  +3130 253 5773 Wed-Fri
http://intamap.geo.uu.nl/~paul




More information about the R-help mailing list