如何将 for 循环转换为 R 中的函数
How to convert a for loop to function in R
我正在尝试将 for 循环转换为基于 c("country", "continent")
的组汇总统计功能。任何帮助将不胜感激,非常感谢。
library(gapminder)
library(purr)
cont <- unique(gapminder$continent)
df <- NULL
temp <- NULL
for(i in 1:(length(cont))) {
temp <- gapminder[gapminder$continent == cont[i], ]
#df[[i]] <- temp
df[[i]] <- temp %>% split(.$continent) %>% map(summary)
}
df
预期答案
my.function(gapminder, c("country", "continent"))
dplyr
和 purrr
解决方案怎么样?
library(dplyr)
library(tidyr)
gapminder %>%
group_by(country, continent) %>%
group_split(.keep = TRUE) %>%
map(summary)
我正在尝试将 for 循环转换为基于 c("country", "continent")
的组汇总统计功能。任何帮助将不胜感激,非常感谢。
library(gapminder)
library(purr)
cont <- unique(gapminder$continent)
df <- NULL
temp <- NULL
for(i in 1:(length(cont))) {
temp <- gapminder[gapminder$continent == cont[i], ]
#df[[i]] <- temp
df[[i]] <- temp %>% split(.$continent) %>% map(summary)
}
df
预期答案
my.function(gapminder, c("country", "continent"))
dplyr
和 purrr
解决方案怎么样?
library(dplyr)
library(tidyr)
gapminder %>%
group_by(country, continent) %>%
group_split(.keep = TRUE) %>%
map(summary)