1
$\begingroup$

I tried to group a set of elements and to calculate the row means

If my list has more than one element, it works fine:

tapply(colnames(myMA), c(1,1,1,2,2,2,3,3,4,4), list)    
myMAmean <- sapply(myList, function(x) rowMeans(myMA[,x]))

However, in my data some of the rows are unique:

myList <- tapply(colnames(myMA), c(1,1,1,2,2,2,3,3,4,5), list)
myMAmean <- sapply(myList, function(x) rowMeans(myMA[,x]))

Notice the 4 & 5 it makes them as unique so if I run this it says

"Error in rowMeans(myMA[, x]) : 
  'x' must be an array of at least two dimensions"

I don't want to run a loop. Is there any solutions for this?

$\endgroup$
6
$\begingroup$

You can prevent the loss of the dimension attribute when using "[" with drop=FALSE:

tapply(colnames(myMA), c(1,1,1,2,2,2,3,3,4,4), list)
myMAmean <- sapply(myList, function(x) rowMeans(myMA[,x, drop=FALSE]))
$\endgroup$
0

Not the answer you're looking for? Browse other questions tagged or ask your own question.