Here is a further improvement on sourcing code and 
data from the same file, namely, the sourced file
no longer needs to specify its name and location.
(Instead, my.stdin grabs this from the environment
within the source command, which is one of its 
ancestors.)

It also occurred to me that the use of my.stdin() 
does have one potential advantage over stdin(), 
even assuming that the problem with stdin() not 
working in sourced files is ultimately addressed in R.
In the case where the data is lengthy, it might be 
desirable to place the data at the end of the code 
so as not to break it up.  The data read by my.stdin() 
can be placed anywhere in the file.  

In the example below, the data for x is placed right 
after the statement which reads in x but the data for 
y and z are placed at the end of this file.  The file 
and path of the file are no longer explicitly specified.


# source the following file from R

my.stdin <- function( tag, this.file = eval.parent(quote(file),n=3) )
  textConnection( sub(tag, "", grep(tag,readLines(this.file),value=T)) )

x <- read.table( my.stdin("^#x"), header=T )
#x Sex Response # this data has a header
#x Male 1 
#x Male 2 
#x Female 3 
#x Female 4 

y <- read.table( my.stdin("^#y") )
z <- scan( my.stdin("^#z") )

# -- data

#y 3.4 4  # this is first line of y data
#y 3 3 
#y 6 6 

#z 3 5 4 6 7
#z 8

______________________________________________
[EMAIL PROTECTED] mailing list
https://www.stat.math.ethz.ch/mailman/listinfo/r-help

Reply via email to