Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

Is their a way to rename the columns of all the dataframes in my workspace in R

I have been trying to find a way of renaming all the columns of each data frame in the workspace in R. They just need to have the same column names. The code below is an example of two data frames (cars and trucks) that will have column names "1:10". However, I have about so many data frames and want to automatically do that.

names(cars) <- c(1:10)
names(trucks) <- c(1:10)

Thanks in advance!

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

>Solution :

Here is one way to do it. Below I just used mtcars as an example and had one vector in my global env to show you can ignore other objects. First I create a list containing the names of the dfs in the global env. Then I use lapply to set the names to 1 to the length of columns in the data. I name the list the names of the original data.frames and use list2env to export the list to the global env.

mt1 <- mtcars

mt2 <- mtcars

v1 <- 1

dfslist <- ls()[sapply(ls(), function(x){class(get(x))}) == "data.frame"]

l1 <- lapply(dfslist,function(x){
   setNames(get(x),1:ncol(get(x)))
})

names(l1) <- dfslist

list2env(l1, .GlobalEnv)
Add a comment

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading