I would skip the intermediate step and use a function that is designed to deliver what you want, namely tapply
. Using agsudy's data:
> x.mean <- with(dat, tapply(x, list(A=A,B=B), mean))
> x.mean
B
A 2 3 4 5
1 0.3671088 0.4531040 0.5942483 0.8013453
2 0.4776386 0.6115361 0.7907584 0.6607741
3 0.3966482 0.3447879 0.4372367 0.4914243
4 0.2779789 0.6780573 0.4087858 0.4205421
5 0.6288597 0.6924584 0.6508705 0.5648296
If you really wanted to use the intermediate step you can also use tapply
with either the I
or c
functions to do the rearrangement:
with(tab, tapply(x.mean, list(A=A,B=B), c))
B
A 2 3 4 5
1 0.3671088 0.4531040 0.5942483 0.8013453
2 0.4776386 0.6115361 0.7907584 0.6607741
3 0.3966482 0.3447879 0.4372367 0.4914243
4 0.2779789 0.6780573 0.4087858 0.4205421
5 0.6288597 0.6924584 0.6508705 0.5648296
> with(tab, tapply(x.mean, list(A,B), I))
2 3 4 5
1 0.3671088 0.4531040 0.5942483 0.8013453
2 0.4776386 0.6115361 0.7907584 0.6607741
3 0.3966482 0.3447879 0.4372367 0.4914243
4 0.2779789 0.6780573 0.4087858 0.4205421
5 0.6288597 0.6924584 0.6508705 0.5648296