如何将指定文本文件转换为R data.frame?读取时出现报错
That error pops up because the file you're trying to read doesn't use single spaces as consistent separators—fields like player names contain spaces themselves, so using sep=' ' splits those names into multiple columns, throwing off the column count vs. the header. Here are a few reliable fixes:
Option 1: Use data.table::fread (Most Hassle-Free)
fread is great at auto-detecting messy separators, so it'll handle the mixed spacing in this file without extra configuration:
# Install and load the package if you haven't already install.packages("data.table") library(data.table) # Read the data y <- fread("https://afltables.com/afl/stats/biglists/bg2.txt", skip = 1)
Option 2: Adjust read.table Parameters
If you prefer base R, tweak the sep argument to let R handle multiple spaces as a single separator, and add fill=TRUE to account for any minor row inconsistencies:
y <- read.table("https://afltables.com/afl/stats/biglists/bg2.txt", skip = 1, header = TRUE, sep = "", # Treats one or more spaces/tabs as a separator stringsAsFactors = FALSE, # Keeps text as character strings (modern default in R 4.0+) fill = TRUE)
Option 3: Use readr::read_table
The readr package (part of the tidyverse) also handles whitespace-separated files smoothly:
install.packages("readr") library(readr) y <- read_table("https://afltables.com/afl/stats/biglists/bg2.txt", skip = 1)
Why Your Original Code Failed
When you set sep=' ', R interprets every single space as a column separator. Since player names (like "Gary Ablett Sr.") have spaces inside them, this splits one name field into multiple columns, making the number of elements in rows like line 3 not match the 30 columns defined by the header. Using a separator that accounts for multiple spaces (or letting auto-detect tools do the work) fixes this.
内容的提问来源于stack exchange,提问作者Harpreet Singh

