rm167
rm167

Reputation: 1247

combining matrix by name

I have a set of matrix named gof_1_1, gof_1_2, ..... ,gof_1_24. I want to combine all of them in to one matrix along the columns. So am using the following code

do.call(cbind,mget(ls(pattern = paste("gof",1,"[0-9]",sep="_"), globalenv())))

It combines the matrix, but problem is they are not in an order. They go like this gof_1_1 , gof_1_11, gof_1_12, ..... , gof_1_19, gof_1_2, gof_1_21 and so on. So I edited the ls() as shown below

ls(pattern = paste("gof",1,"[0-9][0-9]",sep="_"),globalenv())

Now it's in order,But it starts from gof_1_10, to gof_1_25. Missing gof_1_1 to gof_1_9. Any idea how to edit the above one to call all the matrix in order?

Upvotes: 1

Views: 67

Answers (2)

droopy
droopy

Reputation: 2818

an alternative to the paste0 function :

do.call(cbind, mget(sprintf("gof_1_%s", 1:24)))

Upvotes: 2

flodel
flodel

Reputation: 89057

You can do:

do.call(cbind, mget(paste0("gof_1_", 1:24)))

Otherwise, something more complicated like:

mat.names    <- ls(pattern = paste("gof", 1, "[0-9]", sep="_"), globalenv())
mat.idx      <- as.integer(gsub(".*_", "", mat.names))
sorted.names <- mat.names[order(mat.idx)]
do.call(cbind, mget(sorted.names))

Upvotes: 3

Related Questions