这个错误是不言自明的。您的数据文件的第一行(或第二行,可能是因为您使用的是header = TRUE)中似乎缺少数据。
这是一个小例子:
## Create a small dataset to play with
cat("V1 V2\nFirst 1 2\nSecond 2\nThird 3 8\n", file="test.txt")
R 自动检测到它应该期望行名加上两列(3 个元素),但它在第 2 行没有找到 3 个元素,所以你得到一个错误:
read.table("test.txt", header = TRUE)
# Error in scan(file, what, nmax, sep, dec, quote, skip, nlines, na.strings, :
# line 2 did not have 3 elements
查看数据文件,看看是否确实有问题:
cat(readLines("test.txt"), sep = "\n")
# V1 V2
# First 1 2
# Second 2
# Third 3 8
可能需要手动更正,或者我们可以假设“第二”行中的第一个值应该在第一列,其他值应该是NA。如果是这种情况,fill = TRUE 足以解决您的问题。
read.table("test.txt", header = TRUE, fill = TRUE)
# V1 V2
# First 1 2
# Second 2 NA
# Third 3 8
即使缺少行名,R 也足够聪明,可以计算出它需要多少元素:
cat("V1 V2\n1\n2 5\n3 8\n", file="test2.txt")
cat(readLines("test2.txt"), sep = "\n")
# V1 V2
# 1
# 2 5
# 3 8
read.table("test2.txt", header = TRUE)
# Error in scan(file, what, nmax, sep, dec, quote, skip, nlines, na.strings, :
# line 1 did not have 2 elements
read.table("test2.txt", header = TRUE, fill = TRUE)
# V1 V2
# 1 1 NA
# 2 2 5
# 3 3 8