使用函数从较大的 Dataframe 中提取 Dataframe ,并进行汇总统计[重复]

ki1q1bka  于 2023-07-31  发布在  其他
关注(0)|答案(1)|浏览(89)

此问题已在此处有答案

Calculate the mean by group(10个答案)
How to sum a variable by group(18个答案)
Apply several summary functions (sum, mean, etc.) on several variables by group in one call(7个答案)
15天前关闭。
我试图从一个较大的 Dataframe 中提取一个汇总值的 Dataframe ,如下所示:

Year = c(2000,2001,2002,2003,2000,2001,2002,2003,2000,2001,2002,2003,2000,2001,2002,2003)
Country_Name = rep(c("Afghanistan", "Brazil", "Germany", "Italy"), each=4)
total_population = c(10,15,13,12,11,16,14,13,12,17,15,14,13,18,16,15)
Life_expectancy = c(60,67,70,73,61,68,71,74,62,69,72,75,2,69,72,75)
Hospitals = rep(c(5,10,15,13), each=4)
GDP = rep(c(5,7,10,8), each=4)

Example <- data.frame(Year=Year, Country=Country_Name, Population=total_population, Life=Life_expectancy, Hospitals=Hospitals, GDP=GDP)

Example

字符串
我想做的是总结这个数据框架,并按国家提取平均人口,平均GDP等。我可以编写代码来获得各个国家的输出:

country_func <- function(x, df){
  #take summary statistics of 4 variables from tidy dataset
  #x denotes the country name
  
  #ave population
  ave_population <- mean(df$`Population`[df$`Country`==x], na.rm=TRUE)
  #median life
  median_life <- median(df$`Life`[df$`Country`==x], na.rm=TRUE)
  #ave hospital beds per 1000
  ave_hospital_beds <- mean(df$`Hospitals`[df$`Country`==x], na.rm=TRUE)
  #Health expenditure per capita
  mean_GDP <- mean(df$`GDP`[df$`Country`==x], na.rm=TRUE )
  
  data.frame(ave_population=ave_population, median_life=median_life, ave_hospital_beds=ave_hospital_beds, mean_GDP=mean_GDP)
}

country_func('Afghanistan', Example)


但我想做的是,函数返回一个数据框,一次性给出四个国家中每一个国家的汇总统计数据,所以一个数据框有4行(每个国家一行),而不是每次都单独执行。
先谢谢你。

6l7fqoea

6l7fqoea1#

请尝试下面的代码

library(tidyverse)

Example %>% 
  summarise(across(c(Population,Hospitals,GDP), ~ mean(.x,na.rm = T), .names = 'mean_{col}'),
            across(Life, ~ median(.x, na.rm=T), .names = 'median_{col}'), .by = Country)

字符串
创建于2023-07-15带有reprex v2.0.2

# A tibble: 4 × 5
  Country     mean_Population mean_Hospitals mean_GDP median_Life
  <chr>                 <dbl>          <dbl>    <dbl>       <dbl>
1 Afghanistan            12.5              5        5        68.5
2 Brazil                 13.5             10        7        69.5
3 Germany                14.5             15       10        70.5
4 Italy                  15.5             13        8        70.5

相关问题