How to average/mean variables in R based on the level of another variable (and save this as a new variable)?

Hello,

I’m adding more information to try to make my question/example reproducible

My variable names will be for this example:
Variable 1: Paper
Variable 2: selectedES.prepost
Need to create Variable 3: averaged.ES

Code for the data

#data for Paper
Paper= c(1, 1, 1, 1, 1, 1, 1, 1, 2, 3, 3, 3, 4, 4, 4, 4, 4, 4, 4, 4, 5, 5, 5, 5, 5, 5, 6, 7, 7, 7, 7, 7, 7, 8, 8, 8, 8, 9, 9, 9 )

#data for selectedES.prepost
selectedES.prepost=c(0.0048, -0.1420, -0.3044, -1.3024, -0.4052, -0.6066, -0.1961, -1.1187, -0.4585, -0.8251, -0.5328, -1.3623, -0.5450, -0.4982, -0.5714, -0.8793, -0.3677, -0.3976, -0.6136, -0.7047, -0.8580, -0.5024, -0.8018, -0.8927, -0.3106, -0.5893, -0.6677, -1.6663, -1.1769, -0.8384, -0.5632, -0.5237, -0.3458, -0.9957, -0.5331, -0.7413, -0.0311, -0.4936, 0.5422, -0.0340)

#creating a test dataset
mydata <- data.frame(Paper,selectedES.prepost)

What I would like to do:

I would like to average the the selectedES.prepost variable, so that for each averages all the values of the Paper variable by levels. For example, for Paper = 1, it should average 0.0048, -0.1420, -0.3044, -1.3024, -0.4052-0.1961, & -1.1187 to get -.05088. Since I have nine unique values for Paper (1, 2, 3, 4, 5, 6, 7, 8, 9), I should get nine averages.
The averages should be the following bolded values (according to excel):

Paper selectedES.prepost averaged.ES
1 0.0048
1 -0.1420
1 -0.3044
1 -1.3024
1 -0.4052
1 -0.6066
1 -0.1961
1 -1.1187 -0.5088
2 -0.4585 -0.4585
3 -0.8251
3 -0.5328
3 -1.3623 -0.9067
4 -0.5450
4 -0.4982
4 -0.5714
4 -0.8793
4 -0.3677
4 -0.3976
4 -0.6136
4 -0.7047 -0.5722
5 -0.8580
5 -0.5024
5 -0.8018
5 -0.8927
5 -0.3106
5 -0.5893 -0.6591
6 -0.6677 -0.6677
7 -1.6663
7 -1.1769
7 -0.8384
7 -0.5632
7 -0.5237
7 -0.3458 -0.8524
8 -0.9957
8 -0.5331
8 -0.7413
8 -0.0311 -0.5753
9 -0.4936
9 0.5422
9 -0.0340 0.0049

1 Like