2009-09-16 12 views
10

Digamos que quiero reproducir un ejemplo publicado en StackOverflow. Algunos han sugerido que los carteles usen dput() to help streamline this process o uno de los datasets available in the base package.¿Cómo puedo cargar datasets de ejemplo en R?

En este caso, sin embargo, supongamos que sólo se ha dado la salida de la trama de datos:

> 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 

¿Tengo otras opciones además de ahorro de esto como un archivo de texto y el uso de read.table()?

Respuesta

8

Aquí hay una opción útil:

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

La mejor práctica para cerrar explícitamente la textConnection, es decir site.data <- read.table (tc <- textConnection ("...")); close (tc) –

12

Esa es una buena solución. Supongo que hay una manera de hacer esto con RCurl, as in this post which scraped off wikipedia.

Pero como un punto más general para la discusión: ¿por qué no utilizamos los datos del paquete "datasets" en R? Entonces todos tendrán los datos al llamar a la función de datos() y hay conjuntos de datos para cubrir la mayoría de los casos.

[Editar]: Pude hacer esto. Es claramente más trabajo (es decir, poco práctico) que su solución. :)

[Editar 2]: Envolví esto en una función y lo probé con otra página.

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 
+1

De acuerdo. Alentar esto sería ideal. –

Cuestiones relacionadas