How to export the definition of an R object to plain text so that others can recreate it?
Asked Answered
C

3

13

Let's say you have this data in R, and you want to post a question on stackoverflow. For others to best help you, it would be nice if they could have a copy of your object (dataframe, vector, etc) to work with.

Let's say your data is in a data frame called site.data

> 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

How do you package it up so that the users can recreate the data exactly as you have it?

You want to do this without having people download a text file and import it.

(Note: These data subsetted from an example of the REvolutions blog)

Credenza answered 12/8, 2009 at 9:22 Comment(1)
very smart to get this in here.Afroamerican
C
20

The dput command writes an ASCII representation. If instead of a filename you put "" it will write it to the console

> dput(site.data,"")
structure(list(site = structure(c(1L, 1L, 1L, 2L, 2L, 2L, 3L, 
3L, 3L), .Label = c("ALBEN", "ALDER", "AMERI"), class = "factor"), 
    year = c(5L, 10L, 20L, 5L, 10L, 20L, 5L, 10L, 20L), peak = c(101529.6, 
    117483.4, 132960.9, 6561.3, 7897.1, 9208.1, 43656.5, 51475.3, 
    58854.4)), .Names = c("site", "year", "peak"), row.names = c(1L, 
2L, 3L, 8L, 9L, 10L, 15L, 16L, 17L), class = "data.frame")

Just copy the structure and put it after "site.data=" in your example code and people will be able to recreate the data frame exactly as you have it.

Credenza answered 12/8, 2009 at 9:27 Comment(0)
P
6

Actually, in your original example, the way you've pasted your data in column format works just fine. I just copied your text from the web page, and did this (using OS X so I have the nice "paste" command):

> site.data <- read.table(pipe("pbpaste"))

For toy data like something posted as a test case, this is often the best approach. To be extra-precise, dput() is good, as dggoldst says.

Philander answered 12/8, 2009 at 16:40 Comment(0)
R
3

Another way, similar to Ken's is using the clipboard (on windows, and possibly linux). I would copy your code and run

> site.data <- read.table("clipboard", header=T)
> 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
Rusell answered 12/8, 2010 at 9:30 Comment(0)

© 2022 - 2024 — McMap. All rights reserved.