Home > OS >  Replace character in all dataframes in the environment
Replace character in all dataframes in the environment

Time:11-26

I am running a function that returns several datasets in the environment to me. However, these datasets all have a space in their name. Is there a way to replace the space in each dataframe in the global environment with another symbol? I will have 100 datasets in my global environment, so it would be tedious to manually rename them all. I have tried to come up with a solution using assign and str_replace_all but it hasn't worked so far.

MRE:

`Data frame` <- data.frame(x = sample(1:100, 10, replace = T), y = sample(letters[1:24], 10, replace = T))
`Shame data` <- data.frame(x = sample(1:100, 10, replace = T), y = sample(letters[1:24], 10, replace = T))
`Lambda dito` <- data.frame(x = sample(1:100, 10, replace = T), y = sample(letters[1:24], 10, replace = T))

CodePudding user response:

The following is an adaptation of a recent answer of mine to a R-Help question. See also this answer.
You can get all objects to be changed into a list, change the list's names attribute and assign back to the .GlobalEnv. Something like the following.

# create a vector of names of the objects
# whose names are to be changed
obj_names <- ls(pattern = " ")

# get the objects into a list
tmp_list <- mget(obj_names, envir = .GlobalEnv)
# change the list's names
names(tmp_list) <- sub("  ", "_", obj_names)
# assign them to the global environment
list2env(tmp_list, envir = .GlobalEnv)

# clean up
rm(tmp_list)
rm(list = obj_names)

CodePudding user response:

We could use clean_names function and apply it to all dataframes in the environment:

library(janitor) # for clean_names function

dfs <- Filter(function(x) is(x, "data.frame"), mget(ls()))

lapply(dfs, clean_names)
  •  Tags:  
  • r
  • Related