Skip to content
Prev 246954 / 398503 Next

replace values in array with means of certain values in array

On Mon, Jan 10, 2011 at 03:21:18PM +0100, joke R wrote:
Let me suggest to consider the following approach, which avoids the
first line of the above code, computes the means in a different way and
puts them back using the second line of the above code.

First, transform A into a matrix, where the first two dimensions 
represent the rows and the remaining dimensions represent the columns.
This does not reorder the elements of the array, only changes the
dimension information.

  A1 <- matrix(A, nrow=3*3, ncol=2)

Compute the means

  B1 <- c(B)
  C1 <- rowsum(A1, group=B1)/c(table(B1))

Put the means to the required positions

  for(a in 1:3){
    C[B==a] <- rep(C1[a, ], each=sum(B==a))
  }

I hope this can help.

Petr Savicky.