【问题标题】:read.table not working for importing a .datread.table 不适用于导入 .dat
【发布时间】:2026-01-08 04:05:02
【问题描述】:

我正在尝试使用read.table 命令从互联网上的.dat 文件导入数据集。格式化文件时我通常没有问题,例如:

A B
1 2
3 4

但是这个数据集是格式化的

A B A B
1 2 3 4
5 6 7 8

(您可以在这里找到我遇到问题的数据集:https://www2.isye.gatech.edu/~jeffwu/book/data/BrainandBodyWeight.dat

我当前的代码行是:

Data2 = read.table("https://www2.isye.gatech.edu/~jeffwu/book/data/BrainandBodyWeight.dat", header = TRUE)

我得到的错误是:

扫描错误(file = file,what = what,sep = sep,quote = quote,dec = dec, : 第 1 行没有 12 个元素

【问题讨论】:

  • 如果您只是想按原样阅读,则在 read.table 中使用 fill=TRUE 参数,read.table("https://www2.isye.gatech.edu/~jeffwu/book/data/BrainandBodyWeight.dat", header = TRUE, fill = TRUE),因为后面的列不包含任何值,它将填充 NAs
  • @PKumar 可以消除错误,但我只需要两列。数据集只有两个列名,但显示为 6 个不同的列,每个名称显示两次。我正在尝试将所有数据放入相应的列中

标签: r read.table


【解决方案1】:

问题是标题行中有空格,所以用skip = 1跳过它。

从那里,我们可以使用重复的逻辑向量 c(TRUE, FALSE)c(FALSE, TRUE) 提取偶数行和奇数行。

数据的最后一行有一些空值,所以删除那些带有complete.cases()的值。

data <- read.table("https://www2.isye.gatech.edu/~jeffwu/book/data/BrainandBodyWeight.dat",
                   header = FALSE, fill = TRUE, skip = 1)

result <- data.frame(Body.Wt = unname(unlist(data[,c(T,F)])),
                     Brain.Wt = unname(unlist(data[,c(F,T)])))

result <- result[complete.cases(result),]
head(result)
  Body.Wt Brain.Wt
1   3.385     44.5
2   0.480     15.5
3   1.350      8.1
4 465.000    423.0
5  36.330    119.5
6  27.660    115.0

【讨论】:

    最近更新 更多