1

I have three dataframes EC_Data, ED_Data, and ST_data all of them have the same column names and more specifically, after 4th column has Year named colums from 2006 to 2015

So I create a new list that has all three dataframes:

Alldata = list(EC_Data, ED_Data, ST_Data)

So I tried to rename all the columns in a for loop like below...

for(x in seq_along(Alldata))
{
  for(j in seq_along(Alldata[[x]]))
  {
    if(j>4)
    {
      names(colnames(Alldata[[x]][j])) <- paste("X", substr(colnames(Alldata[[x]][j]), start = 1, stop = 5),sep="")
      print(colnames(Alldata[[x]][j]))
    }
  }
}

But nothing happens...

I cannot understand why, because when I try to call the names of every list, for example with

view(colnames(Alldata[[2]])) 

the names seems to be exactly what I want to see

Can someone help me to understand the reason that this loop doesn't work and what can I use instead of this?

Thank you

1 Answers1

0

If we want to rename all the columns use lapply to loop over the list, paste with the substr of the existing column names and assign them with setNames

Alldata <- lapply(Alldata, function(x) 
      setNames(x, paste0("X", substr(colnames(x), 1, 5))))

Or using a for loop

for(i in seq_along(Alldata)) {
      Alldata[[i]] <- setNames(Alldata[[i]], 
           paste0("X", substr(colnames(Alldata[[i]]), 1, 5))
  }
akrun
  • 874,273
  • 37
  • 540
  • 662