假设我想重现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()之外,我还有其他选择吗?

有帮助吗?

解决方案 2

这是一个方便的选项:

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"))

其他提示

这是一个很好的解决方案。我猜有一种方法可以用RCurl做到这一点,在这篇文章中删除了维基百科

但作为更一般的讨论点:为什么我们不仅仅使用来自“数据集”的数据。包裹在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
许可以下: CC-BY-SA归因
不隶属于 StackOverflow
scroll top