1

I have 18 uniform dataframes and would like to change the column names of each of these dataframes to the same column names. Here is a working example for just 2 but I would like this to scale.

df1 <- data.frame("value1" = 1:10, "value2" = 1)
df2 <- data.frame("value1" = 1:10, "value2" = 2)
column.names <- c("new1", "new2")
df.list <- as.list(df1, df2)

So far I have tried both lapply and a for loop

df.list <- lapply(df.list, function(x) {
  colnames(x) <- column.names
  x
})
for (i in seq_along(df.list)) {
  colnames(df.list[[i]]) <- column.names
}

but neither work and both produce the following error

Error in `colnames<-`(`*tmp*`, value = column.names) : 
  attempt to set 'colnames' on an object with less than two dimensions

Any help would be greatly appreciated.

Dave_D
  • 13
  • 3

1 Answers1

1

We don't need as.list as the as.list converts each unit element to a list and it only takes a single argument. According to ?as.list

as.list(x, ...)

x - object to be coerced or tested.

So, what it will do is to create a list from the columns of 'df1' and not take 'df2' i.e.

as.list(df1, df2)
#$value1
# [1]  1  2  3  4  5  6  7  8  9 10

#$value2
# [1] 1 1 1 1 1 1 1 1 1 1

Note that these are just the columns of 'df1'. To place both the objects in list, use the list

df.list <-  list(df1, df2)
Community
  • 1
  • 1
akrun
  • 874,273
  • 37
  • 540
  • 662
  • Great! That fixed it up perfect. Can't believe it was something that simple. Now the problem I am running into is that these dataframes with the changed names are now stored inside the list. Is there an easy way to store them in the environment, outside of the list? – Dave_D Oct 04 '19 at 18:57