Hello, I reviewed my code and this will work now for any number of successive "TA", I hope:
b=matrix(1:64, ncol=4) rownames(b)=rep(c("AA","AT","TA","TT"),each=4) key <- rownames(b) key[key == "AT"] <- "TA" c <- b rownames(c)=key for(i in 2:I(nrow(c))) { if(rownames(c)[i]=="TA" & rownames(c)[i-1]=="TA") { c[i,] <- colSums(c[i:I(i-1),]) c[i-1,]<-NA}} # sums the rows and replace the used rows by NA values c <- c[apply(c,1,function(x)any(!is.na(x))),] # removes the rows with NA values c Rock Rocko22 wrote: > > In the first reply, what was calculated was the overall means by group > (amino acids). It does not work for a larger database. > I am quite really new to R, and I worked on your question just to learn > how to manipulate data with R. > The following seems to work. The code could be made a lot more elegant and > straightforward, but it works only when there is no more than two > successive "TA": > > Let's try with a matrix "b" that contains more rows than in your example: > > b=matrix(1:32, ncol=4) > rownames(b)=rep(c("AA","AT","TA","TT"),2) > key <- rownames(b) > key[key == "AT"] <- "TA" > rownames(b)=key > > for(i in 1:I(nrow(b)-1)) { > if(rownames(b)[i]=="TA" & rownames(b)[i+1]=="TA") { b[i,] <- > colSums(b[i:I(i+1),]) > b[i+1,]<-NA}} # sums the rows and replace the used rows by > NA values > b <- b[order(b[,1],na.last=NA),] # removes the rows with NA values > > Of course, the rows are reordered, and that may be not wanted. The > ordering was just to remove the NA rows. > > Rock :-D > > -- View this message in context: http://www.nabble.com/Looking-for-a-quick-way-to-combine-rows-in-a-matrix-tp23491348p23520900.html Sent from the R help mailing list archive at Nabble.com. ______________________________________________ R-help@r-project.org mailing list https://stat.ethz.ch/mailman/listinfo/r-help PLEASE do read the posting guide http://www.R-project.org/posting-guide.html and provide commented, minimal, self-contained, reproducible code.