[R] Programcode and data in the same textfile

Ernst Hansen erhansen at math.ku.dk
Thu Jun 12 18:42:39 CEST 2003


Thomas W Blackwell writes:
 > 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.
 > 


Nice thinking , Thomas, and good fun indeed.  To take this slightly
further, we can hack the history mechanism to read off the name of the
file being sourced.  If the following lines

  MyHistory <- function() {
    ## basically the first few lines of history()

    file1 <- tempfile("Rrawhist")
    savehistory(file1)
    rawhist <- scan(file1, what = "", quiet = TRUE, sep = "\n")
    unlink(file1)
    rawhist[length(rawhist)]
    }

  cat(strsplit(strsplit(MyHistory(),
  'source\\(')[[1]][2],'\\)')[[1]][1], '\n')

are placed in the file foo.q, then the call

 source('foo.q')

will produce as output

  'foo.q' 

on the terminal.  Instead of writing it out, it could be piped into
read.table(), and by careful linecounting, it could be combined with
your idea of reading lines, that are commented out in the 'real
reading' of the file.  


Then it indeed does what I wanted to do.  Though my students would 
be horrified...:-)

And, of course, if it is allowed to write the history to a temporary
file and read it again, we might as well write the data to a temporary
file, as has already been suggested by Torsten Hothorn.

Ernst




More information about the R-help mailing list