temor
temor

Reputation: 1029

How to replace values with their mean?

I have two matrices

 A = matrix(c(2, 2, 2, 3, 3, 3),nrow=3,ncol=2) 
> A
      [,1] [,2]
[1,]    2    3
[2,]    2    3
[3,]    2    3
B = matrix(c(2, 4, 3, 1, 5, 7),nrow=3, ncol=2) 
> B 
      [,1] [,2]
[1,]    2    1
[2,]    4    5
[3,]    3    7

take the mean of all values in B that correspond to 3 in B: Create a matrix with only the means: Wanted matrix:

    C

        [,1] [,2]
 [1,]    3    4.3
 [2,]    3    4.3
 [3,]    3    4.3

Upvotes: 0

Views: 71

Answers (2)

Andri Signorell
Andri Signorell

Reputation: 1309

What about:

A <- matrix(c(2, 2, 2, 3, 3, 2, 3, 2), nrow=4, ncol=2) 
B <- matrix(c(2, 4, 3, 1, 5, 7, 4, 2), nrow=4, ncol=2) 

matrix(tapply(B, A, mean)[as.character(A)], nrow=nrow(A))

?

Upvotes: 1

Martin Schmelzer
Martin Schmelzer

Reputation: 23919

When the groups are not column specific this might help:

A <- matrix(   c(2, 2, 2, 3, 3, 3),nrow=3,ncol=2) 
B <- matrix(c(2, 4, 3, 1, 5, 7),nrow=3, ncol=2) 
C <- matrix(nrow = dim(A)[1], ncol=dim(A)[2])

groups <- unique(c(A))
for(group in groups) {
  C[which(A==group)] <- mean(B[which(A==group)])
}

If A contains NAvalues, then use

groups <- na.omit(unique(c(A)))

Upvotes: 1

Related Questions