2

For example I got a set of data with 3 levels,namely 1,2,3
a and b are two 3*5 matrices as shown below:

a <- matrix(c(0.1,0.2,0.3,0.3,0.2,0.1,0.1,0.2,0.3,0.3,0.2,0.1,0.1,0.2,0.3),3)

#     [,1] [,2] [,3] [,4] [,5]
#[1,]  0.1  0.3  0.1  0.3  0.1
#[2,]  0.2  0.2  0.2  0.2  0.2
#[3,]  0.3  0.1  0.3  0.1  0.3

b <- matrix(rep(c(1,2,3,1),c(5,6,2,2)),nrow=3,byrow=TRUE)

#     [,1] [,2] [,3] [,4] [,5]
#[1,]    1    1    1    1    1
#[2,]    2    2    2    2    2
#[3,]    2    3    3    1    1

z4 <- tapply(a[,4],as.factor(b[,4]),mean)
z4

  1   2
0.2 0.2 

In this example the output just has 2 levels,I want to store z4 into a vector with 3 entries,i.e. (0.2,0.2,0) with 3 levels shows 0.

How could I do that? Please do not use any loop structure for simplicity.

thelatemail
  • 91,185
  • 12
  • 128
  • 188
  • 2
    Hi, welcome to SO. Since you are new here, you might want to read [**how to make a great reproducible example**](http://stackoverflow.com/q/5963269/1478381) and update your question accordingly. – Simon O'Hanlon Dec 21 '14 at 22:35
  • 2
    In the absence of reproducible code, maybe you want: `tapply(a[,4], factor(b[,4],levels=1:3),mean)` ? – thelatemail Dec 21 '14 at 22:52
  • Well done for an initial edit attempting to show us your data. Welcome to StackOverflow! – Simon O'Hanlon Dec 22 '14 at 00:52

1 Answers1

1

You can try

> z4 <- tapply(a[,4], factor(b[,4], levels = c(1, 2, 3)), mean)
> z4[is.na(z4)] <- 0
> z4
  1   2   3 
0.2 0.2 0.0 
JACKY88
  • 3,391
  • 5
  • 32
  • 48