[R] Looking for a quick way to combine rows in a matrix

Chris Stubben stubben at lanl.gov
Wed May 13 18:44:46 CEST 2009


You can automate this step
>key[key == "AT"] <- "TA"

## 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:
> 
> Try this:
> 
>> key <- rownames(a)
>> key[key == "AT"] <- "TA"
>> do.call(rbind, by(a, key, colSums))
>    V2 V3 V4 V5
> AA  1  5  9 13
> TA  5 13 21 29
> TT  4  8 12 16
> 
> 
> On Mon, May 11, 2009 at 4:53 PM, Crosby, Jacy R
> <Jacy.R.Crosby at uth.tmc.edu>wrote:
> 
>> I'm working with genotype data in a frequency table:
>>
>> > a=matrix(1:16, nrow=4)
>> > rownames(a)=c("AA","AT","TA","TT")
>> > a
>>   [,1] [,2] [,3] [,4]
>> AA    1    5    9   13
>> AT    2    6   10   14
>> TA    3    7   11   15
>> TT    4    8   12   16
>>
>> 'AT' and 'TA' are essentially the same, and I'd like to combine (add) the
>> rows to reflect this. The final matrix should be:
>>
>>   [,1] [,2] [,3] [,4]
>> AA    1    5    9   13
>> AT    5    13   21   29
>> TT    4    8   12   16
>>
>> Is there a fast way to do this?
>>
>> Thanks in advance!
>>
>> Jacy Crosby
>> jacy.r.crosby at uth.tmc.edu
>>
> 

-- 
View this message in context: http://www.nabble.com/Looking-for-a-quick-way-to-combine-rows-in-a-matrix-tp23491348p23525634.html
Sent from the R help mailing list archive at Nabble.com.




More information about the R-help mailing list