[R] How to create "special" (source) file

Gabor Grothendieck ggrothendieck at gmail.com
Mon Jan 2 14:56:54 CET 2006


1. You can use dput.  Suppose x is a data frame.  Then dput(x)
will output x as R code.   e.g.

> dput(head(iris))
structure(list(Sepal.Length = c(5.1, 4.9, 4.7, 4.6, 5, 5.4),
    Sepal.Width = c(3.5, 3, 3.2, 3.1, 3.6, 3.9), Petal.Length = c(1.4,
    1.4, 1.3, 1.5, 1.4, 1.7), Petal.Width = c(0.2, 0.2, 0.2,
    0.2, 0.2, 0.4), Species = structure(c(1, 1, 1, 1, 1, 1), .Label =
c("setosa",
    "versicolor", "virginica"), class = "factor")), .Names = c("Sepal.Length",
"Sepal.Width", "Petal.Length", "Petal.Width", "Species"), row.names = c("1",
"2", "3", "4", "5", "6"), class = "data.frame")

You can now copy and paste iris.head <- ...the output you just got...
into your script, i.e. you can now put this into your script:

iris.head <- structure(list(Sepal.Length = c(5.1, 4.9, 4.7, 4.6, 5, 5.4),
    Sepal.Width = c(3.5, 3, 3.2, 3.1, 3.6, 3.9), Petal.Length = c(1.4,
    1.4, 1.3, 1.5, 1.4, 1.7), Petal.Width = c(0.2, 0.2, 0.2,
    0.2, 0.2, 0.4), Species = structure(c(1, 1, 1, 1, 1, 1), .Label =
c("setosa",
    "versicolor", "virginica"), class = "factor")), .Names = c("Sepal.Length",
"Sepal.Width", "Petal.Length", "Petal.Width", "Species"), row.names = c("1",
"2", "3", "4", "5", "6"), class = "data.frame")


2. Another more readable way is to do this:

Lines <- "Sepal.Length Sepal.Width Petal.Length Petal.Width Species
          5.1         3.5          1.4         0.2  setosa
          4.9         3.0          1.4         0.2  setosa
          4.7         3.2          1.3         0.2  setosa
          4.6         3.1          1.5         0.2  setosa
          5.0         3.6          1.4         0.2  setosa
          5.4         3.9          1.7         0.4  setosa"
iris.head <- read.table(textConnection(Lines), header = TRUE)


On 1/2/06, Eduardo Esteves <eesteves at ualg.pt> wrote:
> Dear All,
>
> I'm a Marine Biologist using R (in a most informal and applied way) for a couple of years. Actually, I've been using R to analyse the results supporting my thesis. I would like to put together (in the same file) the data (.txt files) and the scripts files (.R files) for each chapter. How can I do this?
>
> Thanks in advance, Eduardo Esteves




More information about the R-help mailing list