4

I want to be able to loop over multiple objects in my environment and do some data cleaning on each data frame. Is there a more efficient way to do what I am doing below in 1 call?

df1 %>%
clean_names()

df2 %>% 
clean_names()

df3 %>%
clean_names()

etc.
bodega18
  • 596
  • 2
  • 13

3 Answers3

6

Base R

library(janitor) # for clean_names function
dfs <- Filter(function(x) is(x, "data.frame"), mget(ls()))

lapply(dfs, clean_names)
TarJae
  • 72,363
  • 6
  • 19
  • 66
  • 2
    Although I use `is.x` fuctions a lot, I did not know this `is()`function. Seems very usefull to have a universal `is()`. Thanks – GuedesBF Sep 09 '21 at 21:47
  • @TarJae Works, but when I run the second line of code it just prints the now "cleaned data frames" to the console. How do I make sure the clean names are stored in the environment objects? – bodega18 Sep 10 '21 at 12:53
  • assign it to an object like `x1 <- lapply(dfs, clean_names)` – TarJae Nov 13 '21 at 04:21
5

In addition to akrun´s answer, you can also filter objects from your global environment by class. I recommend you store the updated dataframe in a list, not in the global environment, but in case you want that you can use list2env.

library(purrr)

mget(ls()) %>%
keep(is.data.frame) %>%
map(janitor::clean_names) %>%
##(DISCLAIMER - this replaces the original data.frames in your global environment, and could be dangerous:)
list2env(envir = .GlobalEnv)
GuedesBF
  • 8,409
  • 5
  • 19
  • 37
  • How do I make this store the cleaned names in my environment objects, and not just print to the console? – bodega18 Sep 10 '21 at 13:21
  • I strongly recommend you keep the objects in a list, and not the Global Env. Should you really want to get them back into the global env, see my updated answer – GuedesBF Sep 10 '21 at 21:57
4

Get all the objects created in the environment with mget into a list and then loop over the list and apply the function

library(purrr)
library(dplyr)
library(janitor)
out <- map(mget(ls(pattern = '^df\\d+$')), ~ .x %>%
      clean_names())

The pattern in ls subset the object names based on the regex pattern that check for objects with names that starts (^) with df followed by one or more digits (\\d+) at the end ($) of the string

akrun
  • 874,273
  • 37
  • 540
  • 662