Matrix to list of matrix group by column names in R -
i have matrix 6000 columns , each column belongs 1 of 100 "groups" need. need convert matrix list 100 smaller matrices. toy example of have:
mat = cbind(c(2,2,2),c(3,3,3),c(4,4,4),c(1,1,1)) colnames(mat) = c("2018.3 1","2018.3 2","2019.1 1","2019.2 2")
so "group" identified last name of each colname, here there 2 groups. result need like:
list(cbind(c(2,2,2),c(4,4,4)),cbind(c(3,3,3),c(1,1,1)))
i've been thinking , think should this:
lapply(do.call(cbind,sapply(something here find columns in each group)))
but haven't figure out how it.
#obtain last part of each column names groups = sapply(strsplit(x = colnames(mat), split = " "), function(x) x[2]) #go through each unique column name , extract corresponding columns lapply(unique(groups), function(x) mat[,which(groups == x)]) #[[1]] # 2018.3 1 2019.1 1 #[1,] 2 4 #[2,] 2 4 #[3,] 2 4 #[[2]] # 2018.3 2 2019.2 2 #[1,] 3 1 #[2,] 3 1 #[3,] 3 1
or
lapply(split(1:ncol(mat), sapply(strsplit(x = colnames(mat), split = " "), function(x) x[2])), function(i) mat[,i]) #$`1` # 2018.3 1 2019.1 1 #[1,] 2 4 #[2,] 2 4 #[3,] 2 4 #$`2` # 2018.3 2 2019.2 2 #[1,] 3 1 #[2,] 3 1 #[3,] 3 1
Comments
Post a Comment