0

Let's say we have 2 vectors:

x <- c(1,2,2,2,2,2,3,3,4,3,4,3,4,5,5)
y <- c(40,228,280,252,211,226,235,240,179,175,197,203,227,258,240)

Now I want to sum the elements in y corresponding to the value in x and divide them by the number of occurences in x to store it accordingly:

40, 239.4, 213.25, 201, 249

For example (228 + 280 + 252 + 211 + 226)/5 = 239.4

I'd be thankful if someone could help me.

tacoman
  • 882
  • 6
  • 10

1 Answers1

0

This base R solution could help you with tapply():

tapply(y,x, mean)

Output:

   1      2      3      4      5 
 40.00 239.40 213.25 201.00 249.00 

If you want to save the results in another vector you could use z <- as.vector(tapply(y, x, mean))

Duck
  • 39,058
  • 13
  • 42
  • 84