[R] Programcode and data in the same textfile
Thomas W Blackwell
tblackw at umich.edu
Thu Jun 12 17:39:34 CEST 2003
Ernst -
Here's a solution which works for me, and seems to do
what you want. It's a bit of a hack, since it requires
you, the author, to know in advance what file path name
the student will have saved the file as. In my example,
this will be "./r.source.file", and this includes one
blank line before the first assignment statement below.
It also requires knowing how many lines of code precede
the data lines. But it _is_ a one-file solution, as
requested. Put the following 9 or 10 lines into a
file named "r.source.file", then source it.
data.01 <- read.table(file="r.source.file", header=T,
skip=4, comment.char="")[-1]
# junk Sex Response
# Male 1
# Male 2
# Female 3
# Female 4
I'm quite surprised no one else has suggested this already.
- tom blackwell - u michigan medical school - ann arbor -
On Thu, 12 Jun 2003, Ernst Hansen wrote:
> PROBLEM: Is there any way I can have a single textfile that contains both
> a) data b) programcode
> The program should act on the data, if the textfile is source()'ed
> into R.
>
> BOUNDARY CONDITION: I want the data written in the textfile in exactly
> the same format as I would use, if I had data in a separate textfile,
> to be read by read.table(). something like
>
> Sex Respons
> Male 1
> Male 2
> Female 3
> Female 4
>
> MOTIVATION: I frequently find myself distributing small chunks of code
> to my students, along with data on which the code can work.
>
> As an example, I might want to demonstrate how model.matrix() treats
> interactions, in a certain setting. For that I need a dataframe that
> is complex enough to exhibit the behaviour I want, but still so small
> that the model.matrix is easily understood. So I make such a dataframe.
>
> I am trying to distribute this dataframe along with my code, in a way
> that is as simple as possible to USE for the students (hence the
> one-file boundary condition) and to READ (hence the non-transposition
> boundary condition).
>
> Ernst Hansen
> Department of Statistics
> University of Copenhagen
More information about the R-help
mailing list