You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

如何将指定文本文件转换为R data.frame?读取时出现报错

Fixing the "line 3 did not have 30 elements" Error When Reading AFL Tables Data

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

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.05.15 03:26:57