How to Fix in R: incomplete final line found by readTableHeader


One warning you may encounter in R is:

Warning message:
In read.table(file = file, header = header, sep = sep, quote = quote,  :
  incomplete final line found by readTableHeader on 'my_data.csv' 

This warning occurs when you attempt to read a CSV file into R but the final line in the file is not blank.

It’s important to note that this is only a warning message and not an error. Even when this message appears, your file will still be imported into R.

This tutorial shares how to avoid this warning altogether.

How to Reproduce the Warning

Suppose I have the following CSV file called my_data.csv that I’d like to import into R:

Now suppose I attempt to use the following code to import this CSV file into R:

#import CSV file
df <- read.csv('my_data.csv')

Warning message:
In read.table(file = file, header = header, sep = sep, quote = quote,  :
  incomplete final line found by readTableHeader on 'my_data.csv'

I receive a warning message because the final line in the CSV file is not blank.

However, the file was still imported successfully:

#view imported data frame
df

  team points assists
1    A     20       5
2    B     15       3
3    C     19       9
4    D     20       3.

Method 1: How to Avoid the Warning

One way to avoid this warning is to simply place the read.csv() function inside a suppressWarnings() function:

#import CSV file and suppress any warnings
df <- suppressWarnings(read.csv('my_data.csv'))

#view data frame
df

  team points assists
1    A     20       5
2    B     15       3
3    C     19       9
4    D     20       3

This time we’re able to import the CSV file without any warnings.

The benefit of this approach is that we don’t have to modify the file directly.

The drawback of this approach is that if there are more serious warnings we need to know about when importing the file, we won’t be able to see them.

Method 2: How to Avoid the Warning

Another way to avoid this warning is to modify the CSV file directly.

Specifically, we can go to the last line of the file and press Enter to create a new blank line at the end of the file:

Now when we import the CSV file, we don’t receive any warnings:

#import CSV file
df <- read.csv('my_data.csv')

#view data frame
df

  team points assists
1    A     20       5
2    B     15       3
3    C     19       9
4    D     20       3

The benefit of this approach is that we’ll still be able to see any other warnings when importing the file.

The drawback of this approach is that we have to modify the file directly rather than simply using a programmatic solution.

Additional Resources

The following tutorials explain how to perform other common operations in R:

How to Use readLines() Function in R
How to Import CSV Files into R
How to Use read.table in R

Leave a Reply

Your email address will not be published.