philbo_baggins
philbo_baggins

Reputation: 179

Can R read.csv return an empty data frame?

I have a project where I am iterating through thousands of text files and reading these into a large data frame. I was able to get all of the files into a list named filenames. The loop looks something like this:

for(i in 1:length(filenames))
{
   text <- read.csv(filenames[i], header = T)
   //Analysis on text
}

Unfortunately, several of the text files are completely empty (too many to manually delete). Read.csv throws an error when it encounters one of these files, and the for loop terminates. Is there any way that I can get around this error by having read.csv return an empty data frame instead of an error? Thanks.

Upvotes: 0

Views: 823

Answers (1)

okurr_Z
okurr_Z

Reputation: 71

you can instead put the instruction in try and the loop will continue. Code:

 for(i in 1:length(filenames))
  {
   try(
    text <- read.csv(filenames[i], header = T)
    //Analysis on text
      )
  } 

Upvotes: 3

Related Questions