このエラーは一目瞭然です。データ ファイルの最初の行 (または を使用しているため、場合によっては 2 行目) にデータが欠落しているようです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 は行名と 2 つの列 (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
手動での修正が必要になる場合があります。または、「2 番目」の行の最初の値が最初の列にあり、他の値が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