Home > OS >  function to run over multiple data frames, can't get df in list back into df out of list
function to run over multiple data frames, can't get df in list back into df out of list

Time:02-15

I am using a function to apply the same command over a few different dataframes. I put it in a list to run it. While the function works and the dataframs in the list change appropriately, I don't know how to get it out of the list, so that the mtcars and mtcars2 in the global environment are also changed. What I want is for the dataframes in the list to overwrite the dataframes in the glboal environment, so that mtcars and mtcars2 (in the global environment) are changed by the function. Here is dummy data to approximate what I'm trying:

data(mtcars)
mtcars2 <- mtcars
df.list <- list(mtcars, mtcars2)

pad2 <- c("mpg", "cyl") #maybe ends_with("state_code") in your code?
pad3 <- c("vs", "gear")

lapply(1:length(df.list), function(x){
  df.list[[x]] <<- df.list[[x]] %>% mutate(across(c(pad2,pad3),as.character)) %>% 
    mutate(across(pad2,~str_pad(.x, 2, "left", pad="0")),
           across(pad3,~str_pad(.x, 3, "left", pad="0")))
})

CodePudding user response:

Create a named list

names(df.list) <- c("mtcars", "mtcars2")

and then use list2env on the output

library(purrr)
library(dplyr)
library(stringr)
df.list <- map(df.list,  ~ .x %>%
       mutate(across(all_of(c(pad2, pad3)),  as.character)) %>%
        mutate(across(all_of(pad2), ~str_pad(.x, 2, "left", pad="0")),
           across(all_of(pad3), ~str_pad(.x, 3, "left", pad="0")))
)
list2env(df.list, .GlobalEnv)

-checking the individual objects

> head(mtcars)
                   mpg cyl disp  hp drat    wt  qsec  vs am gear carb
Mazda RX4           21  06  160 110 3.90 2.620 16.46 000  1  004    4
Mazda RX4 Wag       21  06  160 110 3.90 2.875 17.02 000  1  004    4
Datsun 710        22.8  04  108  93 3.85 2.320 18.61 001  1  004    1
Hornet 4 Drive    21.4  06  258 110 3.08 3.215 19.44 001  0  003    1
Hornet Sportabout 18.7  08  360 175 3.15 3.440 17.02 000  0  003    2
Valiant           18.1  06  225 105 2.76 3.460 20.22 001  0  003    1
> head(mtcars2)
                   mpg cyl disp  hp drat    wt  qsec  vs am gear carb
Mazda RX4           21  06  160 110 3.90 2.620 16.46 000  1  004    4
Mazda RX4 Wag       21  06  160 110 3.90 2.875 17.02 000  1  004    4
Datsun 710        22.8  04  108  93 3.85 2.320 18.61 001  1  004    1
Hornet 4 Drive    21.4  06  258 110 3.08 3.215 19.44 001  0  003    1
Hornet Sportabout 18.7  08  360 175 3.15 3.440 17.02 000  0  003    2
Valiant           18.1  06  225 105 2.76 3.460 20.22 001  0  003    1
  •  Tags:  
  • r
  • Related