I have some data frames which are loaded from the tabs of an Excel file, which have spaces in their name.
Name <- c("Jon", "Bill", "Maria", "Ben", "Tina")
Age <- c(23, 41, 32, 58, 26)
df <- data.frame(Name, Age)
`df A` <- data.frame(Name, Age)
`df B` <- data.frame(Name, Age)
I would like to clean or repair the object names that have spaces, so that they become:
dfA
dfB
Without specifically referring to these dataframes.
How should I do this?
CodePudding user response:
Since there are no easy way to rename objects in an environment, you can select them, put them in a list and rename them there, then put them back in the environment:
objs <- mget(ls(pattern = "df "))
rm(list = ls(pattern = "df "))
names(objs) <- gsub(" ", "", names(objs))
list2env(objs, envir = .GlobalEnv)
CodePudding user response:
Before you assign each sheet to a data frame, you can change the names of the sheets with openxlsx:
library(openxlxs)
wb <- loadWorkbook("/home/example.xlsx")
newnames <- gsub(" ","", names(wb))
names(wb) <- newnames
CodePudding user response:
One possible way to solve your problem:
for(el in ls(pattern="df ")) assign(gsub(" ", "", el), get(el))