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

1.8k views Asked by At

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.

2

There are 2 answers

2
arvi1000 On BEST ANSWER

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')
0
MrFlick On

While I do agree it would be much better to keep your data.frames in a list rather than creating a bunch of variables in your global environment, you can also set names when you read the files in

assign(paste("import",i,sep=""), 
    read.csv(files[i], header=FALSE, col.names=c("xxxx", "yyyy")))

Using assign() isn't very "R-like".