Reputation: 29
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.
Upvotes: 2
Views: 372
Reputation: 3557
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
Upvotes: 1