0

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!

1 Answers1

1

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)
Mike
  • 2,845
  • 1
  • 10
  • 29
  • 1
    You can shorten your `dfslist` definition quite a bit using `mget` and the built-in `Filter` function: `dfslist – Gregor Thomas Jun 02 '22 at 19:44
  • 1
    Also, in general, don't use `class(x) ==` to check the class of things. Objects may have several classes, and some classes extend others through inheritance. That's why we have the `is.class.name` functions. – Gregor Thomas Jun 02 '22 at 19:46
  • 1
    Though I guess I misunderstood. `dfslist` is just the names of the data frames. I'd recommend skipping that step and going straight to the list of data frames, as in my first comment. – Gregor Thomas Jun 02 '22 at 19:50
  • Thank you Mike! Thank you Gregor! Thank you Allan! – Mustafa Kamal Jun 02 '22 at 19:50
  • 1
    With the edits, not `dfslist` is the actual data frames, so your `lapply `can be simplified too, `dfslist – Gregor Thomas Jun 02 '22 at 20:29