1

在此先感谢您的帮助。本质上,当我遇到这个时,我正在测试从网站上获取数据:http: //lib.stat.cmu.edu/datasets/sleep。我按照以下方式进行:

(A) 了解数据(在 R 中):我基本上输入了以下内容

readLines("http://lib.stat.cmu.edu/datasets/sleep", n=100)

(B) 我注意到我想要的数据确实从第 51 行开始,所以我编写了以下代码:

sleep_table <- read.table("http://lib.stat.cmu.edu/datasets/sleep", header=FALSE, skip=50)

(C) 我收到以下错误:

Error in scan(file, what, nmax, sep, dec, quote, skip, nlines, na.strings,  : 
line 1 did not have 14 elements

我得到上述方法的地方来自另一个关于堆栈溢出的问题(将 dat 文件导入 R)。但是,这个问题涉及 .dat 文件,而我的问题是特定 URL 上的数据。我想知道的是如何将第 51 行的数据(如果您使用 readLines)获取到没有标题的数据框中(稍后我将使用 colnames(sleep_table) <- c("etc ."、"etc2"、"etc3"...)。

4

2 回答 2

3

由于“Lesser short-tailed shrew”和“Pig”的分隔符空格数不相等,并且其他字段不是制表符分隔的,因此 read.table 将无济于事。但幸运的是,这似乎是固定空间。请注意,该解决方案并不完整,因为记录末尾有几行令人讨厌的行,您可能必须将字符转换为数字,但这只是一个简单的练习。

# 123456789012345689012345678901234568901234567890123456890123456789012345689012345678901234568901234567890123456890
# African elephant         6654.000 5712.000  -999.0  -999.0     3.3    38.6   645.0       3       5       3
# African giant pouched rat   1.000    6.600     6.3     2.0     8.3     4.5    42.0       3       1       3
sleep_table <- read.fwf("http://lib.stat.cmu.edu/datasets/sleep", widths = c(25,rep(8,10)),
                          header=FALSE, skip=51)
于 2013-05-29T16:51:38.990 回答
3

使用好的行以一个数字字段结尾并且除第一个字段之外的每个字段都是数字的事实:

URL <- "http://lib.stat.cmu.edu/datasets/sleep"
L <- readLines(URL)

# lines ending in a one digit field
good.lines <- grep(" \\d$", L, value = TRUE)

# insert commas before numeric fields
lines.csv <- gsub("( [-0-9.])", ",\\1", good.lines)

# re-read
DF <- read.table(text = lines.csv, sep = ",", as.is = TRUE, strip.white = TRUE, 
         na.strings = "-999.0")

如果您也对标题感兴趣,这里有一些代码。如果您对标题不感兴趣,请忽略其余部分。

# get headings - of the lines starting at left edge these are the ncol(DF) lines
#  starting with the one containing "species"
headings0 <- grep("^[^ ]", L, value = TRUE)
i <- grep("species", headings0)
headings <- headings0[seq(i, length = ncol(DF))]

# The headings are a bit long so we shorten them to the first word
names(DF) <- sub(" .*$", "", headings)

这给出了:

> head(DF)
                    species     body  brain slow paradoxical total maximum
1          African elephant 6654.000 5712.0   NA          NA   3.3    38.6
2 African giant pouched rat    1.000    6.6  6.3         2.0   8.3     4.5
3                Arctic Fox    3.385   44.5   NA          NA  12.5    14.0
4    Arctic ground squirrel    0.920    5.7   NA          NA  16.5      NA
5            Asian elephant 2547.000 4603.0  2.1         1.8   3.9    69.0
6                    Baboon   10.550  179.5  9.1         0.7   9.8    27.0
  gestation predation sleep overall
1       645         3     5       3
2        42         3     1       3
3        60         1     1       1
4        25         5     2       3
5       624         3     5       4
6       180         4     4       4

更新:空白修剪的小幅简化

更新2:缩短标题

更新 3:添加na.strings = "-999.0"

于 2013-05-29T17:03:50.793 回答