[R] vector-factor operation
Berwin A Turlach
berwin at maths.uwa.edu.au
Fri Apr 14 08:34:49 CEST 2006
G'day Murray,
>>>>> "MJ" == Murray Jorgensen <maj at stats.waikato.ac.nz> writes:
MJ> I found myself wanting to average a vector [vec] within each
MJ> level of a factor [Fac], returning a vector of the same length
MJ> as vec.
I presume that the vector that you want as result should not just have
the same length as vec, should it? :-)
MJ> But there must be another way to do this, and it would be good
MJ> to be able to apply other functions than mean() in this way.
Something like:
> Fac <- sample(gl(2,4))
> Fac
[1] 2 1 1 2 2 1 1 2
Levels: 1 2
> vec <- rnorm(length(Fac))
> tapply(vec, Fac, mean)
1 2
-0.6435816 -0.9267021
> tapply(vec, Fac, mean)[Fac]
2 1 1 2 2 1 1
-0.9267021 -0.6435816 -0.6435816 -0.9267021 -0.9267021 -0.6435816 -0.6435816
2
-0.9267021
> tapply(vec, Fac, sum)[Fac]
2 1 1 2 2 1 1 2
-3.706808 -2.574326 -2.574326 -3.706808 -3.706808 -2.574326 -2.574326 -3.706808
Cheers,
Berwin
========================== Full address ============================
Berwin A Turlach Tel.: +61 (8) 6488 3338 (secr)
School of Mathematics and Statistics +61 (8) 6488 3383 (self)
The University of Western Australia FAX : +61 (8) 6488 1028
35 Stirling Highway
Crawley WA 6009 e-mail: berwin at maths.uwa.edu.au
Australia http://www.maths.uwa.edu.au/~berwin
More information about the R-help
mailing list