首页 > 解决方案 > 收集、平均和结果

问题描述

向你们所有的好人问好,

我正在查看 OECD-PISA 发布的不同国家的数学和科学分数。当我查看不同学生取得的不同分数时,我发现一行名称为“选定的国家和地区”。搜索名字后,我在《早期优势:构建适合幼儿的系统》一书中找到了答案。这一行代表来自选定国家/地区的一组学生的平均分数 [1.Australia, 2.England, 3. Findland, 4.Hong Kong, 5.the Republic of Korea, 6.Singapore]。

假设我有以下跨国数据,

year  country          GDP_growth   R&D_exp  Education_spending
2000  Australia        3.4          1.9      4.8
2001  Australia        2.1          0.9      5.0
2002  Australia        3.0          0.9      6.2
2000  England          3.6          3.9      7.8
2001  England          3.5          4.6      7.8
2002  England          3.2          4.0      7.9
2000  Findland         1.9          0.2      8.0
2001  Findland         2.2          0.7      8.1
2002  Findland         2.7          1.0      8.2

我的问题:我如何收集这些选定国家的 GDP 增长、研发支出……,计算平均值,并将结果添加到每年的新行中?我想在所有年份(2000 年到 2018 年)都执行上述步骤。

因此,到最后,我将有新行名称为“选定国家和司法管辖区”的不同年份,其最终结果(汇总和平均)如下:

year     country                                GDP_growth  R&D_exp    Education_spending
2000     Selected countries and jurisdications   3.5         3.1        6.1
2001     Selected countries and jurisdications
...

请分享您对如何完成这样的事情的想法和想法。

谢谢你。

标签: r

解决方案


你可以使用aggregate(). 对于选择,只需使用一个country.set向量。事先使用语法有效的名称是明智的,您可以使用make.names().

names(dat) <- make.names(names(dat))

country.set <- c("Australia", "England")

cbind(aggregate(cbind(GDP_growth, R.D_exp, Education_spending) ~ year, 
          dat[dat$country %in% country.set, ], mean), 
      country="Selected countries and jurisdications")[c(1, 5, 2:4)]  # some ordering
#   year                               country GDP_growth R.D_exp Education_spending
# 1 2000 Selected countries and jurisdications        3.5    2.90               6.30
# 2 2001 Selected countries and jurisdications        2.8    2.75               6.40
# 3 2002 Selected countries and jurisdications        3.1    2.45               7.05

数据:

dat <- structure(list(year = c(2000L, 2001L, 2002L, 2000L, 2001L, 2002L, 
2000L, 2001L, 2002L), country = c("Australia", "Australia", "Australia", 
"England", "England", "England", "Findland", "Findland", "Findland"
), GDP_growth = c(3.4, 2.1, 3, 3.6, 3.5, 3.2, 1.9, 2.2, 2.7), 
    `R&D_exp` = c(1.9, 0.9, 0.9, 3.9, 4.6, 4, 0.2, 0.7, 1), Education_spending = c(4.8, 
    5, 6.2, 7.8, 7.8, 7.9, 8, 8.1, 8.2)), row.names = c(NA, -9L
), class = "data.frame")

推荐阅读