0

I have 20 excel files containing city level data for each year. I imported them in a list because I thought it will be easier to loop over them. The first task that I wanted to do is to change the name of the second column of each file. If, for a single file I do:

#data is a list of data tables/frames. Example:
data<-list(a = data.frame(1:2,3:4),b = data.frame(5:8,15:18) )

#renaming first column of a (works)
names(data[[1]])[2]<-"ABC"

I am able to rename the column. To do batch editing I wanted to write a function to be used in lapply. The function should be a simple version of the above thing:

 rename <-function(df){
  names(df)[2]<-"XYZ"}

Rename(data[[1]]) however, does nothing to the second column. Any ideas why?

IRTFM
  • 258,963
  • 21
  • 364
  • 487
Djpengo
  • 379
  • 2
  • 14
  • 1
    Welcome to SO. The question is not reproducible. Please try to create a small but complete representative example otherwise it's very likely the question will be closed. This https://stackoverflow.com/questions/5963269/how-to-make-a-great-r-reproducible-example may help you do that. That link is in the SO R FAQ https://stackoverflow.com/tags/r/info which all new posters are expected to read before posting. – hrbrmstr Oct 14 '18 at 20:40
  • Thos are not data.tables. They are dataframes. – IRTFM Oct 14 '18 at 21:02
  • Yes, I edited the question, sorry... But it's the same if you create a random data frame. – Djpengo Oct 14 '18 at 21:05

1 Answers1

0

You need to return the full modified object at each iteration:

data <- lapply( data, function(x) {names(x)[2]<-"ABC"; x})
data
#---------
[[1]]
  X1.2 ABC
1    1   3
2    2   4

[[2]]
  X5.8 ABC
1    5  15
2    6  16
3    7  17
4    8  18

I'm sure this is a duplicate but I don't know what the right search terms might be, so I'm just answering it .... again.

IRTFM
  • 258,963
  • 21
  • 364
  • 487