Loop Over Multiple Environment Objects R

Viewed 247

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.
3 Answers

Base R

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

lapply(dfs, clean_names)

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)

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

Related