Skip to content
Prev 303494 / 398506 Next

Column Extraction from 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
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}}