combining matrix by name

南楼画角 提交于 2019-12-08 06:56:57

问题


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?


回答1:


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))



回答2:


an alternative to the paste0 function :

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


来源:https://stackoverflow.com/questions/22682851/combining-matrix-by-name

标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!