Search code examples
rpasteassignnames

R: Using the "names" function on a dataset created within a loop


I am using a for loop to read in multiple csv files and naming the datasets import1, import2, etc. For example:

assign(paste("import",i,sep=""), read.csv(files[i], header=FALSE))

However, I now want to rename the variables in each dataset. I have tried the following:

names(as.name(paste("import",i,sep=""))) <- c("xxxx", "yyyy")

But get the error "target of assignment expands to non-language object". (I need to change the name of variables in each dataset within the loop as the variable names need to be different in each dataset).

Any suggestions on how to do this would be much appreciated.

Thanks.


Solution

  • A better approach would be to read the files into a list of data.frames, instead of one data.frame object per file. Assuming files is the vector of file names (as you imply above):

    import <- lapply(files, read.csv, header=FALSE)
    

    Then if you want to operate on each data.frame in the list using a loop, you easily can:

    for (i in seq_along(import)) names(import[[i]]) <- c('xxx', 'yyy')