+1 vote
in Programming Languages by (7.3k points)

I have the following two sequences: 

a<- c('a', 'b', 'c', 'b', 'b', 'a', 'c', 'a', 'a', 'b', 'c')

b<- c(11,12,13,1,34,15,34,54,21,51,87)

The values in b correspond to the elements in a. I want to calculate average by unique elements in a. How can I do it?

1 Answer

0 votes
by (30.2k points)

You can try one of the following approaches to calculating the mean by the group in R.

1. You can use the function tapply() to apply the mean.

a<- c('a', 'b', 'c', 'b', 'b', 'a', 'c', 'a', 'a', 'b', 'c')
b<- c(11,12,13,1,34,15,34,54,21,51,87)
v1 <- tapply(b, a, mean)

2. You can use the function aggregate() to apply the mean.

a<- c('a', 'b', 'c', 'b', 'b', 'a', 'c', 'a', 'a', 'b', 'c')
b<- c(11,12,13,1,34,15,34,54,21,51,87)
v2 <- aggregate(b, by=list(a), FUN = mean)

The above codes will give the following outputs:

> v1
       a        b        c
25.25000 24.50000 44.66667
> v2
  Group.1        x
1       a 25.25000
2       b 24.50000
3       c 44.66667

...