-1

I would like to change all of the column names (V1, V2, V3, ...) in a list of dataframes to the names in a vector of the same length. There are a few very similar questions, but none of them worked for my particular list. Any help is appreciated. The dataframe below (first8) doesn't recognize V1, V2, V3, ....as column names.first8, 19.9 MB.

My vector (colnames) contains 249 names. There are also 249 variables in the list of dataframes.

Column names

I've tried several methods below that have failed yet they worked on similar examples in SO.

> for(i in 1:length(first8)){
+ colnames(first8[[i]]) <- colnames
+ }
Error in `colnames<-`(`*tmp*`, value = c("FILEID", "FILETYPE", "STUSAB",  : 
  'names' attribute [249] must be the same length as the vector [8]


> test <- lapply(first8, setNames, colnames)
Error in FUN(X[[i]], ...) : 
  'names' attribute [249] must be the same length as the vector [8]



>Map(function(df, vec) setNames(df, n), first8, colnames)
 Show Traceback

 Rerun with Debug
 Error in setNames(df, n) : 
  'names' attribute [249] must be the same length as the vector [8] 

What am I doing wrong? Thank you.

user3067851
  • 524
  • 1
  • 6
  • 20

2 Answers2

2

We can try

lapply(first8, function(x) setNames(x, vec1))

Or without the anonymous function call

lapply(first8, setNames, vec1)

data

set.seed(24)
first8 <- lapply(1:5, function(i) 
   as.data.frame(matrix(sample(1:10, 8*5, replace=TRUE), ncol=8)))
vec1 <- LETTERS[1:8]


 

 
Community
  • 1
  • 1
akrun
  • 874,273
  • 37
  • 540
  • 662
0

`colnames' accepts a list of character vectors. You don't need to iterate through them.

colnames(first8) <- colnames[1:8];

See ?colnames for details.

Mekki MacAulay
  • 1,727
  • 2
  • 12
  • 23
  • neither works....perhaps because each of the dataframes in my list have a different number of variables. The first one has 8 and the other 241. colnames comes up NULL on my list and akrun's. – user3067851 Jan 06 '16 at 18:26
  • I am going to research exactly why this particular code worked and the others didn't on my list of DFs, but I'm sharing for whoever may gain from it. This was taken from another SO post with similar question. I still believe a few of the previous answers didn't work because most of the examples used lists that contain DFs with the same number of variables in each.... test <- lapply (first8, function(x) {colnames(x)[1:length(x)] <-first8Names[1:length(x)];x } ) (http://stackoverflow.com/questions/33567101/using-lapply-to-change-column-names-of-a-list-of-data-frames) – user3067851 Jan 06 '16 at 19:26