Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to rbind matrices based on objects names?

Tags:

r

rbind

I have several matrices that I would like to rbind in a single summary one. They are objects product of different functions and they have share a pattern in their names.

What I want to do is to tell R to look for all the objects with that common pattern and then rbind them.

Assuming these matrices exist:

commonname.N1<-matrix(nrow=2,ncol=3)
commonname.N2<-matrix(nrow=2,ncol=3)
commonname.M1<-matrix(nrow=2,ncol=3)

I tried something like this to get them:

mats<-grep(x= ls(pos=1), pattern="commonname.", value=TRUE)
mats
[1] "commonname.N1" "commonname.N2" "commonname.M1"    

What I can't figure out is how to tell rbind to use that as argument. Basically I would something that gives the same matrix than what rbind(commonname.N1, commonname.N2, commonname.M1) would do in this example.

I have tried things on the line of

mats<-toString(mats)
rbind(mats2)

but that just creates a matrix with the different objects as names.

A similar question was asked here, but:

mats<-as.list(mats)
do.call(what=rbind, args=as.list(mats))

doesn't do the job.

Sorry if there is something basic I'm missing somewhere, but I can't figure it out and I'm relatively new to R.

like image 707
A.Mstt Avatar asked Mar 22 '23 20:03

A.Mstt


1 Answers

Use mget:

do.call(rbind,mget(mats))
like image 68
Thomas Avatar answered Apr 10 '23 11:04

Thomas