[R] read.csv(stdin(),...) with sweave

Gabor Grothendieck ggrothendieck at myway.com
Fri Oct 29 01:29:27 CEST 2004


 <ockham <at> gmx.net> writes:

: 
: hello, 
: 
: i would like to read in a small amount of csv data directly from a
: sweave-enabled latex document. i tried 
: 
: \begin{Scode}{fig=FALSE,echo=TRUE}
: timeval <- read.csv(stdin(),nrows=2)
: t1,t2,t3,t4
: 24.23,26.79,23.47,23.97
: \end{Scode}
: 
: but apparently the stdin() approach doesnt't work as I get
: 
: Writing to file test.tex
: Processing code chunks ...
:  1 : echo term verbatim
: 
: Error:  chunk 1
: Error in parse(file, n, text, prompt) : parse error
: 
: Any help very much appreciated...

Here a couple of solutions:

1. You could use the my.stdin function from:

   https://stat.ethz.ch/pipermail/r-help/2003-June/033622.html

like this in sweave (untested):

my.stdin <- function( tag, this.file = eval.parent(quote(file),n=3) )
  textConnection( sub(tag, "", grep(tag,readLines(this.file),value=T)) )
timeval <- read.csv(my.stdin("#x"),this.file=sweave.path.file,nrows=2)
#x t1,t2,t3,t4
#x 24.23,26.79,23.47,23.97

where sweave.path.file is the path/filename of your sweave file.


2. A second possibility is to just read it in into R, display it
using dput and copy and paste that into your sweave document.


a. Read your data in using R (note that nrows is the number
   of _data_ rows) and display it using dput:

	R> timeval <- read.csv(stdin(), nrows=1) 
	0: t1,t2,t3,t4
	1: 24.23,26.79,23.47,23.97

	R> dput(timeval)
	structure(list(t1 = 24.23, t2 = 26.79, t3 = 23.47, t4 = 23.97), 
	.Names = c("t1", "t2", "t3", "t4"), class = "data.frame", row.names 
= "1")

b. Copy the output of dput into the clipboard (i.e. select
   it with the mouse and initiate a copy ,e.g. ctrl-c on
   Windows).

c. In the editor with your sweave document enter

	   timeval <- 

   and press Paste, e.g. ctrl-V in windows.




More information about the R-help mailing list