0

With the following code, I am reading multiple csv files into dataframes.

setwd("/path/to/files")

filenames <- gsub("\\.csv$","", list.files(pattern="\\.csv$"))

for(i in filenames){
  assign(i, read.csv(paste(i, ".csv", sep="")))
}

When I try to access them in the following code

for (i in filenames) {
    imanDavenportTest(i)
}

I get the following error

Error in apply(data, MARGIN = 1, FUN = f) : 
  dim(X) must have a positive length

can someone help me?

alistaire
  • 38,696
  • 4
  • 60
  • 94

2 Answers2

2

Your "filenames" are simply character strings representing the names of the data imported from read.csv. You need to get the data from these named objects.

So try:

for(i in filenames){
  imanDavenportTest(get(i))
}
Edward
  • 8,978
  • 2
  • 9
  • 24
2

Edward's answer is correct. But I wanted to add a note as you are going about this in a quite complicated way and not taking full advantage of R.

There's no reason to use assign here. You can read in all your data in one go and have the results stored as a single object (a list) rather than having N objects polluting your workspace. For example:

# read files in your directory
file_ls <- list.files('.', pattern=".csv$")

# use lapply to read each file and create a list of data frames
data_ls <- lapply(file_ls, read.csv)

# perform the test on each element of the list
lapply(data_ls, imanDavenportTest)

assign is often adopted by people that are coming from languages that have global variables but it doesn't take advantage of R's object-orientated functional programming. IMHO, using assign in this manner creates code that is hard to read and fragile to maintain.

Muon
  • 971
  • 6
  • 25