Reputation: 13
I am working with a large survey dataset, comprised of several countries and years. I am trying to create a new variable that is the mean trust score of each country in a particular year. I want to create a line graph showing the patterns of trust for each country across the years. I have a variable which is 'country years' which determines the country and the year of the survey. When I use the code below, I just get a variable which has the overall mean of all trust scores, rather than specific country_year mean trust scores.
data<-data%>%
group_by(country_year)%>%
mutate(averagetrust = mean(trust))
My dataset looks something like this, but with 31 countries and 342 country/year combinations. The trust scores are individual trust scores for each respondents
# country year country_year trust
# 1 Austria 2002 AT2002 4
# 2 Austria 2002 AT2002 9
# 55 Belgium 2002 BE2002 7
# 56 Belgium 2002 BE2002 3
# 91 Austria 2005 AT2005 2
# 91 Austria 2005 AT2005 6
# 141 Belgium 2005 BE2005 5
# 142 Belgium 2005 BE2005 9
Upvotes: 1
Views: 71
Reputation: 9260
Try it with summarise
library(gapminder)
library(tidyverse)
gapminder%>%
group_by(country, year)%>%
filter(country %in% c("Germany", "Belgium", "France")) %>%
summarise(averagetrust = mean(pop, na.rm = T)) %>%
ggplot(aes(x = year, y = averagetrust, color = country)) +
geom_line()
Upvotes: 0