10

假设我想重现发布在 StackOverflow 上的示例。有些人建议使用海报dput()来帮助简化此过程基本包中可用的数据集之一

但是,在这种情况下,假设我只得到了数据帧的输出:

> site.data
    site year     peak
1  ALBEN    5 101529.6
2  ALBEN   10 117483.4
3  ALBEN   20 132960.9
8  ALDER    5   6561.3
9  ALDER   10   7897.1
10 ALDER   20   9208.1
15 AMERI    5  43656.5
16 AMERI   10  51475.3
17 AMERI   20  58854.4

除了将其保存为文本文件并使用之外,我还有其他选择read.table()吗?

4

2 回答 2

12

这是一个巧妙的解决方案。我猜有一种方法可以用 RCurl 来做到这一点,就像这篇从 wikipedia 上刮下来的帖子一样

但作为一个更普遍的讨论点:为什么我们不只使用 R 中“数据集”包中的数据呢?然后每个人只要调用 data() 函数就可以获得数据,并且有数据集可以覆盖大多数情况。

[编辑]:我能够做到这一点。这显然比您的解决方案更多工作(即不切实际)。:)

[编辑 2]:我将其包装到一个函数中,并在另一个页面上进行了尝试。

getSOTable <- function(url, code.block=2, raw=FALSE, delimiter="code") {
  require(RCurl)
  require(XML)

  webpage <- getURL(url)
  webpage <- readLines(tc <- textConnection(webpage)); close(tc)
  pagetree <- htmlTreeParse(webpage, error=function(...){}, useInternalNodes = TRUE)
  x <- xpathSApply(pagetree, paste("//*/", delimiter, sep=""), xmlValue)[code.block]  
  if(raw)
    return(strsplit(x, "\n")[[1]])
  else 
    return(read.table(textConnection(strsplit(x, "\n")[[1]][-1])))
}

getSOTable("https://stackoverflow.com/questions/1434897/how-do-i-load-example-datasets-in-r")
    site year     peak
1  ALBEN    5 101529.6
2  ALBEN   10 117483.4
3  ALBEN   20 132960.9
8  ALDER    5   6561.3
9  ALDER   10   7897.1
10 ALDER   20   9208.1
15 AMERI    5  43656.5
16 AMERI   10  51475.3
17 AMERI   20  58854.4

getSOTable("https://stackoverflow.com/questions/1428174/quickly-generate-the-cartesian-product-of-a-matrix", code.block=10)
   X1 X2 X3 X4
1   1 11  1 11
2   1 11  2 12
3   1 11  3 13
4   1 11  4 14
5   1 11  5 15
6   1 11  6 16
7   1 11  7 17
8   1 11  8 18
9   1 11  9 19
10  1 11 10 20
于 2009-09-16T19:12:50.500 回答
8

这是一个方便的选择:

site.data <- read.table(textConnection(
"        site year     peak
1  ALBEN    5 101529.6
2  ALBEN   10 117483.4
3  ALBEN   20 132960.9
8  ALDER    5   6561.3
9  ALDER   10   7897.1
10 ALDER   20   9208.1
15 AMERI    5  43656.5
16 AMERI   10  51475.3
17 AMERI   20  58854.4"))
于 2009-09-16T19:08:28.007 回答