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.
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)
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With