How to Fix in R: more columns than column names


One error you may encounter in R is:

Error in read.table("my_data.csv", header=TRUE) : 
  more columns than column names 

This error usually occurs when you attempt to read a CSV file into R using the read.table() function and fail to specify that the separator (sep) should be a comma.

This tutorial shares exactly how to fix this error.

How to Reproduce the Error

Suppose we have the following CSV file called basketball_data.csv:

Now suppose we attempt to import this file into R using the read.table() function:

#attempt to import CSV into data frame
df <- read.table("basketball_data.csv", header=TRUE) 

Error in read.table("basketball_data.csv", header = TRUE) : 
  more columns than column names

We receive an error because we failed to specify that the values in our file are separated by commas.

Since there are spaces in between the values in the rows of the data frame but not in the header, the read.table() function thinks there is only one column.

Thus, it tells us that there are more columns than column names.

How to Fix the Error

The way to fix this error is to simply use sep=”,” when importing the file:

#import CSV file into data frame
df <- read.table("basketball_data.csv", header=TRUE, sep=",")

#view data frame
df
  team points rebounds
1    A     22       10
2    B     14        9
3    C     29        6
4    D     30        2

We are able to successfully import the CSV file without any errors because we specified that the values in the file are separated by commas.

Alternatively, we could just use read.csv() to import the file if we know that it is a CSV file:

#import CSV file into data frame
df <- read.csv("basketball_data.csv", header=TRUE)

#view data frame
df

  team points rebounds
1  'A'     22       10
2  'B'     14        9
3  'C'     29        6
4  'D'     30        2

Notice that we don’t receive any error when importing the CSV file this time either.

Additional Resources

The following tutorials explain how to troubleshoot other common errors in R:

How to Fix in R: names do not match previous names
How to Fix in R: longer object length is not a multiple of shorter object length
How to Fix in R: contrasts can be applied only to factors with 2 or more levels

Leave a Reply

Your email address will not be published.