创建群体​​平均值的变量

发布于 2025-01-22 09:25:09 字数 788 浏览 0 评论 0原文

我正在与一个大型调查数据集合作,该数据集由几个国家和年份组成。我正在尝试创建一个新变量,这是特定年份中每个国家的平均信任得分。我想创建一个线图,以显示多年来每个国家的信任模式。我有一个变量,即“国家年份”,该变量决定了国家和调查年。 当我使用下面的代码时,我只会得到一个具有所有信任分数的总均值的变量,而不是特定的country_ year均值信任分数。

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

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

如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

扫码二维码加入Web技术交流群

发布评论

需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。

评论(1

挽心 2025-01-29 09:25:09

使用总结尝试一下

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()

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()
~没有更多了~
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文