【问题标题】:How to convert a for loop to function in R如何将for循环转换为R中的函数
【发布时间】:2021-12-29 05:51:00
【问题描述】:

我正在尝试将 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"))

【问题讨论】:

  • 你的 for 循环正确吗?它没有提到国家

标签: r function for-loop data-manipulation


【解决方案1】:

dplyrpurrr 解决方案怎么样?

library(dplyr)
library(tidyr)

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

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2020-06-03
    • 2011-03-25
    • 1970-01-01
    • 1970-01-01
    • 2020-11-02
    • 1970-01-01
    • 2022-10-17
    • 1970-01-01
    相关资源
    最近更新 更多