Search code examples
rtidyverselapplydata-cleaning

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!


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.

    edit based on @gregor suggestion

    mt1 <- mtcars
    
    mt2 <- mtcars
    
    v1 <- 1
    
    dfslist <-  Filter(mget(ls()), f = is.data.frame)
    
    l1 <- lapply(1:length(dfslist),function(x){
       setNames(dfslist[[x]],1:ncol(dfslist[[x]]))
    })
    
    names(l1) <- names(dfslist)
    
    list2env(l1, .GlobalEnv)