[R] (unclassified?) Help Question
jim holtman
jholtman at gmail.com
Sun Jul 17 03:10:41 CEST 2011
Is this what you want (using 'ave'):
> set.seed(1)
> f1 <- gl(2, 1, 10, labels=c("M", "F"))
> f2 <- gl(2, 2, 10, labels=c("H", "L"))
> x <- rnorm(10)
> d <- data.frame(f1, f2, x)
> g <- interaction(f1, f2)
> tapply(x, g, mean)
M.H F.H M.L F.L
0.0929451 -0.3140711 -0.1740998 1.1668028
> g
[1] M.H F.H M.L F.L M.H F.H M.L F.L M.H F.H
Levels: M.H F.H M.L F.L
> d
f1 f2 x
1 M H -0.6264538
2 F H 0.1836433
3 M L -0.8356286
4 F L 1.5952808
5 M H 0.3295078
6 F H -0.8204684
7 M L 0.4874291
8 F L 0.7383247
9 M H 0.5757814
10 F H -0.3053884
> ave(d$x, d$f1, d$f2, FUN = mean)
[1] 0.0929451 -0.3140711 -0.1740998 1.1668028 0.0929451 -0.3140711
-0.1740998 1.1668028 0.0929451
[10] -0.3140711
> d$result <- ave(d$x, d$f1, d$f2, FUN = mean)
> d
f1 f2 x result
1 M H -0.6264538 0.0929451
2 F H 0.1836433 -0.3140711
3 M L -0.8356286 -0.1740998
4 F L 1.5952808 1.1668028
5 M H 0.3295078 0.0929451
6 F H -0.8204684 -0.3140711
7 M L 0.4874291 -0.1740998
8 F L 0.7383247 1.1668028
9 M H 0.5757814 0.0929451
10 F H -0.3053884 -0.3140711
>
On Sat, Jul 16, 2011 at 4:08 PM, Lars Bishop <lars52r at gmail.com> wrote:
> Dear List,
>
> I'd appreciate you guidance for obtaining the desired result shown
> below, by combining tapply(x, g, mean) and g in the example.
>
> Basically, I'm trying to create a vector whose values are based on the
> result from tapply(x, g, mean) but that follow the pattern and length
> given by the factor g. Of course I'm looking for a generic solution
> (i.e, not something that just work for this particualr case).
>
> set.seed(1)
> f1 <- gl(2, 1, 10, labels=c("M", "F"))
> f2 <- gl(2, 2, 10, labels=c("H", "L"))
> x <- rnorm(10)
> d <- data.frame(f1, f2, x)
> g <- interaction(f1, f2)
> tapply(x, g, mean)
>> M.H F.H M.L F.L
>> 0.0929451 -0.3140711 -0.1740998 1.1668028
> g
>> [1] M.H F.H M.L F.L M.H F.H M.L F.L M.H F.H
>> Levels: M.H F.H M.L F.L
>
> Desired result:
>
> x
>> [1] 0.0929451 -0.3140711 -0.1740998 1.1668028 0.0929451 -0.3140711 -0.1740998
>> [8] 1.1668028
>
>
> Thanks for any help!
> Lars.
>
> ______________________________________________
> R-help at r-project.org mailing list
> https://stat.ethz.ch/mailman/listinfo/r-help
> PLEASE do read the posting guide http://www.R-project.org/posting-guide.html
> and provide commented, minimal, self-contained, reproducible code.
>
--
Jim Holtman
Data Munger Guru
What is the problem that you are trying to solve?
More information about the R-help
mailing list