如何在 R 中将 for 循环转换为函数

How to convert a for loop to function in R

提问人:Seyma Kalay 提问时间:11/18/2021 更新时间:11/18/2021 访问量:72

问:

我正在尝试将 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"))
R 函数 for 循环 数据操作

评论

0赞 George Savva 11/18/2021
你的for循环正确吗?它没有提到国家

答:

1赞 Edo 11/18/2021 #1

一个和解决方案呢?dplyrpurrr

library(dplyr)
library(tidyr)

gapminder %>% 
  group_by(country, continent) %>% 
  group_split(.keep = TRUE) %>% 
  map(summary)