53

I am new to R. I am trying to read in a "CSV" file that is space-space delimited. The file does not have headers. It looks like this

Element1 Element2
Element5 Element6 Element7

I am trying to read it in like this:

> mydata <- read.table("/PathTo/file.csv")
Error in scan(file, what, nmax, sep, dec, quote, skip, nlines, na.strings,  : 
  line 1 did not have 14 elements

Why does it expect 14 elements in the first row? How do I import this file?

bernie2436
  • 22,841
  • 49
  • 151
  • 244

2 Answers2

111

read.table wants to return a data.frame, which must have an element in each column. Therefore R expects each row to have the same number of elements and it doesn't fill in empty spaces by default. Try read.table("/PathTo/file.csv" , fill = TRUE ) to fill in the blanks.

e.g.

read.table( text= "Element1 Element2
Element5 Element6 Element7" , fill = TRUE , header = FALSE )
#        V1       V2       V3
#1 Element1 Element2         
#2 Element5 Element6 Element7

A note on whether or not to set header = FALSE... read.table tries to automatically determine if you have a header row thus:

header is set to TRUE if and only if the first row contains one fewer field than the number of columns

Simon O'Hanlon
  • 58,647
  • 14
  • 142
  • 184
  • +1, but I think you meant to uncomment that second line and I think you meant to add `header = FALSE` considering your sample data, right? – A5C1D2H2I1M1N2O1R2T1 Oct 18 '13 at 17:40
  • @AnandaMahto `header=FALSE` is the default, and yes, shouldn't be an octothorpe in that! Not sure how that ended up there!! EDIT: So given the data you are of course (as usual) right – Simon O'Hanlon Oct 18 '13 at 17:42
  • 2
    I fixed the same issue just using `read.delim()` instead of `read.table()`. – Gian Arauz Nov 04 '21 at 09:57
2

To read characters try

scan("/PathTo/file.csv", "")

If you're reading numeric values, then just use

scan("/PathTo/file.csv")

scan by default will use white space as separator. The type of the second arg defines 'what' to read (defaults to double()).

Fernando
  • 7,785
  • 6
  • 49
  • 81