Skip to content
Prev 180238 / 398506 Next

Looking for a quick way to combine rows in a matrix

You can automate this step
## create a function to reverse a string -- see strsplit help page for this
strReverse function
reverse <- function(x) sapply(lapply(strsplit(x, NULL), rev), paste,
collapse="")

key <- rownames(a)
# combine rownames with reverse (rownames)
n<-cbind(key, rev=reverse(key))
     key  rev 
[1,] "AA" "AA"
[2,] "AT" "TA"
[3,] "TA" "AT"
[4,] "TT" "TT"

# Now just sort the values in the rows   (apply returns column vectors so I
also use t() ) and then run do.call on first column
 n<-t(apply(n,1, sort))

do.call(rbind, by(a, n[,1], colSums)) 
   V1 V2 V3 V4
AA  1  5  9 13
AT  5 13 21 29
TT  4  8 12 16


I often need to combine reverse complement DNA strings, so you could do that
too 

# DNA complement
comp <-  function(x) chartr("ACGT", "TGCA", x)

n<-cbind(key, rev=reverse(comp(key)))  
 n<-t(apply(n,1, sort))
do.call(rbind, by(a, n[,1], colSums)) 
   V1 V2 V3 V4
AA  5 13 21 29   
AT  2  6 10 14
TA  3  7 11 15


Chris Stubben
jholtman wrote: