[R] Column Extraction from matrix

S Ellison S.Ellison at LGCGroup.com
Thu Aug 16 13:13:20 CEST 2012


> -----Original Message-----
> I have a 4 by 100 matrix. I wish to extract each column and 
> make it into a 2 by 2 matrix. 

#make a toy 4x100 matrix:
m <- matrix(rnorm(400), ncol=100)

#use lapply after on-the-fly conversion to a list-like object:
a.list <- lapply(as.data.frame(m),function(x) matrix(x, ncol=2))
	#a list of 4x4 matrices with default names V1...V100

> I also want to assign names for each 2X2 matrix. 
names(a.list) <- paste("a", 1:length(a.list), sep="")
	#a list of 4x4 matrices with default names a1...a100


If you don't care too much about preserving m, set column names on m first, via
colnames(m) <- paste("a", 1:dim(m)[2], sep="")
a.list <- lapply(as.data.frame(m),function(x) matrix(x, ncol=2))
	#now returns the column names set on m


If you really want separate variables cluttering up your workspace  you would need to wrap it into a loop like
for(i in 1:100) assign(paste('a',i, sep=''), matrix(m[,i], ncol=2))

But I would advise against that unless there is very good reason: it is awkward to reference many objects, and if they are in a named (or unnamed) list you can nearly always use various forms of lapply, or loops, applied to the list instead. For example, to get the determinants of all these little matrices
sapply(a.list, det)

works much more simply than some awkward loop code that constructs the variable names, uses get to reference them and then has to find somewhere to put all the determinants.


*******************************************************************
This email and any attachments are confidential. Any use...{{dropped:8}}



More information about the R-help mailing list