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

问题描述 投票:1回答:1

我正在尝试应用一个函数,它接受多个输入(根据手头的问题而变化的列)并将其应用于数据帧列表。我从这个例子中得到了下面的代码:Map with Purrr multiple dataframes and have those modified dataframes as the output并修改它以包含我选择的另一个度量('choice')。但是,此代码会抛出错误“.f(.x [[i]],...)中的错误:未使用的参数(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")
dictionary split group-by dplyr purrr
1个回答
3
投票

修复上面代码的三件事:

  1. 在函数中添加choice作为参数。
  2. 通过删除x <-使您的函数具有输出
  3. 使用tidyeval使“选择”参数有效。

编辑后的代码如下所示:

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))

如果你想留在数据框/ tibble中,那么使用qazxsw poi来创建qazxsw poi可能会有所帮助。

nest
© www.soinside.com 2019 - 2024. All rights reserved.