snn
snn

Reputation: 13

R: Creating Yearly / Within Country Averages

I'm trying to create a mean variable which calculates the mean country-level value for observations within a country across different years.

My data looks like this:

party_id year country position
    101 1984      be     2.75
    101 1988      be     2.75
    101 1992      be     3.33
    101 1996      be     3.67
    102 1984      be     5.80
    102 1988      be     5.80

For example I would like a mean variable which would have the mean position of all parties in Belgium for 1984, and so on.

Upvotes: 0

Views: 958

Answers (1)

cdeterman
cdeterman

Reputation: 19960

Using aggregate you can get the average by country and year

aggregate(position ~ country + year, data = df,  mean)

  country year position
1      be 1984    4.275
2      be 1988    4.275
3      be 1992    3.330
4      be 1996    3.670

Another, perhaps more readable, way is to use dplyr

library(dplyr)
df %>%
  group_by(country, year) %>%
  summarise(mean(position))

Edit - OP request to add variable to data you can use mutate

df %>%
  group_by(country, year) %>%
  mutate(mean(position))

base solution suggested by @bouncyball

merge(x = df,y = aggregate(position~year+country, data = df, FUN = mean), 
      by = c('year','country'))

Upvotes: 2

Related Questions