I'm downloading a data set from

url = "http://robjhyndman.com/tsdldata/misc/kings.dat"

Using read.csv works,

read.csv(url, comment.char="#")  

but read.table

read.table(url, comment.char="#")

gives the error:

Error in scan(file, what, nmax, sep, dec, quote, skip, nlines, na.strings,  : 
  line 2 did not have 8 elements
有帮助吗?

解决方案

If you look at the first few lines of this file you get:

Age of Death of Successive Kings of England
#starting with William the Conqueror
#Source: McNeill, "Interactive Data Analysis"
60
43
67

When you use read.table, the default separator argument is sep="", which the help file explains as:

sep: the field separator character.  Values on each line of the
     file are separated by this character.  If 'sep = ""' (the
     default for 'read.table') the separator is 'white space',
     that is one or more spaces, tabs, newlines or carriage
     returns.

So the first line is treated as eight values. When read.table gets to the numeric values, we get the error:

Error in scan(file, what, nmax, sep, dec, quote, skip, nlines, na.strings,  : 
  line 2 did not have 8 elements

The read.csv function uses the comma as a separator and so the first line is just a single value.

许可以下: CC-BY-SA归因
不隶属于 StackOverflow
scroll top