使用 purrr 将映射函数应用于分组数据框

Apply map function to grouped data frame in with purrr

我正在尝试应用一个函数,该函数接受多个输入(这些输入的列因手头的问题而异)并将其应用于数据框列表。我从这个示例中获取了以下代码: 并将其修改为包含我选择的另一个指标 ('choice')。但是,此代码会引发错误:

Error in .f(.x[[i]], ...) : unused argument (choice = "disp").

理想情况下,我希望能够创建一个分组数据框(使用 group_by 或 split() 并在数据框中的不同组上应用一个函数,但是无法工作这个出来。因此,改为查看数据帧列表。

mtcars2 <- mtcars 

#change one variable just to distinguish them 
mtcars2$mpg <- mtcars2$mpg / 2

#create the list
dflist <- list(mtcars,mtcars2)

#then, a simple function example
my_fun <- function(x) 

{x <- x %>%
  summarise(`sum of mpg` = sum(mpg), 
            `sum of cyl` = sum(cyl),
            `sum of choice` = sum(choice))}

#then, using map, this works and prints the desired results
list_results <- map(dflist,my_fun, choice= "disp")

修复上面代码的三件事:

  1. 在您的函数中添加 choice 作为参数。
  2. 通过删除 x <-
  3. 让您的函数有输出
  4. 使用 tidyeval 使 "choice" 参数有效。

编辑后的代码如下所示:

my_fun <- function(x, choice) 

{x %>%
summarise(`sum of mpg` = sum(mpg), 
          `sum of cyl` = sum(cyl),
          `sum of choice` = sum(!!choice))}

list_results <- map(dflist, my_fun, choice = quo(disp))

如果您想保持在 dataframe/tibble 范围内,那么使用 nest to create list-columns 可能会有所帮助。

mtcars2$group <- sample(c("a", "b", "c"), 32, replace = TRUE)
mtcars2 %>% 
    as_tibble() %>% 
    nest(-group) %>% 
    mutate(out = map(data, my_fun, quo(disp))) %>% 
    unnest(out)