R script - Getting averages
I have two lists. The first list has a finite number of options:
a = [1, 1.5, 2, 2.5, 2, 2.5, 1, 1.5, 1, 2.5]
and then I have another list which has integers
b = [34, 67, 45, 12, 45, 78, 90, 50, 60, 12]
As you can see, in list a, the only possible values are 1, 1.5, 2, and 2.5. Also note that the two lists correspond to each other. So for the first elements, a 1 has a value of 34.
I want to average each of 1, 1.5, 2, and 2.5, depending on the values it has (which are given in b).
So, for exampl开发者_开发百科e, a 2 has a 45 in position 3, and a 45 in position 5. Hence, the average is 45.
How can I do this sort of thing nicely in R?
I assume that a
and b
are really numeric vectors rather than lists -- if not, unlist
them to make them so.
a <- c(1, 1.5, 2, 2.5, 2, 2.5, 1, 1.5, 1, 2.5)
b <- c(34, 67, 45, 12, 45, 78, 90, 50, 60, 12)
tapply(b,a,mean)
result:
1 1.5 2 2.5
61.33333 58.50000 45.00000 34.00000
Two more options, one from base R and the other in plyr
:
> aggregate(b, list(a), mean)
Group.1 x
1 1.0 61.33333
2 1.5 58.50000
3 2.0 45.00000
4 2.5 34.00000
> library(plyr)
> ddply(data.frame(a,b), "a", summarize, meanval = mean(b))
a meanval
1 1.0 61.33333
2 1.5 58.50000
3 2.0 45.00000
4 2.5 34.00000
精彩评论