此问题已在此处有答案:
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行(每个国家一行),而不是每次都单独执行。
先谢谢你。
1条答案
按热度按时间6l7fqoea1#
请尝试下面的代码
字符串
创建于2023-07-15带有reprex v2.0.2
型