user1631306
user1631306

Reputation: 4470

split matrix in R by column name

I have a matrix of 6 columns like:

c_1 C_2 A_1 A_2 D_1 D_2 ..
 2  3  3  3  3  3  3
 4  4  4  4  2  2  2

I want to break this three matrix having same prefixes:

c_1 c_2
2  3
4  4

A_1 A_2
3 3
4 4 

Upvotes: 1

Views: 2790

Answers (3)

Jack Ryan
Jack Ryan

Reputation: 2144

Try something like:

library(stringr)
spl <- read.table(header=TRUE, text='
c_1 C_2 A_1 A_2 D_1 D_2 ..
2  3  3  3  3  3  3
4  4  4  4  2  2  2')
spl
names(spl) <- lapply(names(spl), tolower) # not sure if you want "c_1" w/ "C_2"
lapply(split(data.frame(t(spl)), str_extract(names(spl), "[A-Za-z]")), t)
# $a
# a_1 a_2
# X1   3   3
# X2   4   4
# 
# $c
# c_1 c_2
# X1   2   3
# X2   4   4
# 
# $d
# d_1 d_2
# X1   3   3
# X2   2   2

#or
lapply(split(data.frame(t(spl)), substr(names(spl), 1, 1)), t) # includes ".."

Upvotes: 1

shadow
shadow

Reputation: 22293

It depends a bit what exactly you want to do. Here are a few examples:

mat <- structure(c(3L, 4L, 3L, 4L, 3L, 4L, 3L, 2L, 3L, 2L, 3L, 2L), 
                 .Dim = c(2L,6L), 
                 .Dimnames = list(c("2", "4"), c("c_1", "c_2", "A_1", "A_2","D_1", "D_2")))

If you just want to extract some rows mannually, you can use

mat[,1:2]
mat[,3:4]
mat[,5:6]

In case you want to do this depending on the first letter of the columnname, you can manually choose what column names you want:

mat[,substr(colnames(mat), 1, 1)=="A"]

or you can get a list with all possible columnnames

lst <- lapply(unique(substr(colnames(mat),1,1)), 
          function(x) mat[,substr(colnames(mat), 1, 1)==x])
names(lst) <- unique(substr(colnames(mat),1,1))
lst

Upvotes: 1

joran
joran

Reputation: 173547

Assuming the mixed case lower/upper case c in your matrix is a typo, something like this should work:

m <- matrix(1:12,2,6)
colnames(m) <- paste(rep(letters[1:3],each = 2),1:2,sep = '_')
out <- split.data.frame(t(m),f = substr(rownames(t(m)),1,1))
out <- lapply(out,t)
> out
$a
     a_1 a_2
[1,]   1   3
[2,]   2   4

$b
     b_1 b_2
[1,]   5   7
[2,]   6   8

$c
     c_1 c_2
[1,]   9  11
[2,]  10  12

Upvotes: 5

Related Questions