4

I am trying to read in a file that has 24 column headers, but 14 additional null values. See link: https://www.elections.il.gov/ElectionInformation/CandDataFile.aspx?id=51

Whenever I run the code below, I get the message

"more columns than column names."

I feel like the answer is probably simple. Any idea?

candidates <- read.csv(file = "candidates.txt", sep = ",", 
                        header = TRUE, stringsAsFactors = FALSE)
989
  • 12,579
  • 5
  • 31
  • 53
Aaron Feldman
  • 41
  • 1
  • 1
  • 2
  • 1
    It would help if you post the data. Please take a look at this : http://stackoverflow.com/questions/5963269/how-to-make-a-great-r-reproducible-example Also, I cant open the link you provided. – Sumedh Jul 11 '16 at 16:31

3 Answers3

11

One solution is to read the headers only with one command, the data without header in a second, and then delete excess columns and set the names.

NAMES <- read.table("candidates.txt", nrow = 1, stringsAsFactors = FALSE, sep = ",")
DATA <- read.table("candidates.txt", skip = 1, stringsAsFactors = FALSE, sep = ",")
DATA <- DATA[, 1:24]
names(DATA) <- NAMES 
Richard Telford
  • 9,558
  • 6
  • 38
  • 51
0

I had similar issue while running through docker. So, I had to download the file first then read csv file.

# download data
download.file("https://www.elections.il.gov/ElectionInformation/CandDataFile.aspx?id=51", dest = "candidates.txt")

# load data
gm = read.table("candidates.txt", header = T, stringsAsFactors = F, skipNul = F)

Not_Dave
  • 491
  • 2
  • 8
0

I faced a similar problem and I think the issue was with the header. Because when I deleted the header (a line beginning with a '#' at the beginning of the file), no error would occur. At last, the solution in the link below solved the problem. It sets the parameter 'skip' to 1 to skip the first line of the file (the header).

https://community.rstudio.com/t/more-columns-than-column-names-error/43517

  • 1
    this is not an answer. Link-only answers and "i faced the same problem" posts are not considered answers and should be removed. – GuedesBF Apr 16 '21 at 16:45