I've got a question with the map function from the Purrr package.
- I can successfully pass on a list of data frames to a function using map
- the output remains a list and that's my issue ; I need to have the modified data frames as R objects
As an example with the mtcars dataset:
#I create a second df
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)
)
}
#then, using map, this works and prints the desired results
list_results <- map(dflist,my_fun)
But, I would need to have the modified mtcars and mtcars2 saved as r objects (dataframes).
- Should I add a "save" option of some kind to my function ?
- Should I use map_df or dmap ? (My trials were unsuccessful)
In advance, thanks a lot to all of you !
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.
来源:https://stackoverflow.com/questions/47140756/map-with-purrr-multiple-dataframes-and-have-those-modified-dataframes-as-the-out