Map with Purrr multiple dataframes and have those modified dataframes as the output

好久不见. 提交于 2019-12-06 14:50:45

Here is an attempt:

library(purrr)
library(tidyverse)

mtcars2 <- mtcars 
mtcars2$mpg <- mtcars2$mpg / 2
dflist <- list(mtcars,mtcars2)

To save the objects one would need to give them specific names, and use:

assign("name", object, envir = .GlobalEnv)

here is one way to achieve that:

my_fun <- function(x, list) {
  listi <- list[[x]]
  assign(paste0("object_from_function_", x), dflist[[x]], envir = .GlobalEnv)
  x <- listi %>%
    summarise(`sum of mpg` = sum(mpg), 
              `sum of cyl` = sum(cyl)
    )
  return(x)
}

my_fun has two arguments - seq_along(list) to generate specific names and the list that is to be processed

this saves two objects object_from_function_1 and object_from_function_2:

list_results <- map(seq_along(dflist), my_fun, dflist)

another approach would be to use list2env outside of the map function as akrun suggested

dflist <- list(mtcars,mtcars2)
names(dflist) <- c("mtcars","mtcars2")
list2env(dflist, envir = .GlobalEnv) #this will create two objects `mtcars` and `mtcars2`

and run map after you have created the objects as you have already done.

标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!