Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Loop Over Multiple Environment Objects R

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.
like image 765
bodega18 Avatar asked Dec 05 '22 07:12

bodega18


2 Answers

Base R

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

lapply(dfs, clean_names)
like image 189
TarJae Avatar answered Dec 31 '22 23:12

TarJae


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)
like image 45
GuedesBF Avatar answered Dec 31 '22 21:12

GuedesBF