[R] can't use Sweave in a function?

Duncan Murdoch murdoch at stats.uwo.ca
Fri May 11 03:46:27 CEST 2007


On 10/05/2007 9:08 PM, Tao Shi wrote:
> Hi List,
> 
> Please see the following simple example which illustrate the problem.  I'm 
> using R-2.5.0 in WinXP and
> R2HTML 1.58.
>

The code in an Sweave document needs to be self-contained.  It won't see 
variables in some other R session.

If you want to pass the values of x and y into your document, use save() 
to save them to a file, then load() them in the document.

Duncan Murdoch

> Thanks,
> 
> ....Tao
> 
> 
> #============="test.rnw" =================
> <html>
> 
> <body>
> <div>
> 
> <h1 align=center>Report</h1>
> 
> <p>
> <<echo=FALSE,results=html>>=
>   print(y)
>   print("\n")
>   print(paste("(", x, ")", sep=""))
> @
> </p>
> 
> </div>
> </body>
> </html>
> 
> #============================
> 
> 
> #=========== R session ==================
>> ls()
> character(0)
>> f1 <- function() {
> +   y <- 1:5
> +   x <- "ABC"
> +   Sweave("test.rnw", driver=RweaveHTML)
> + }
>> f1()
> Writing to file test.html
> Processing code chunks ...
> 1 : term html
> 
> Error:  chunk 1
> Error in print(y) : object "y" not found
>> debug(f1)
>> f1()
> debugging in: f1()
> debug: {
>     y <- 1:5
>     x <- "ABC"
>     Sweave("test.rnw", driver = RweaveHTML)
> }
> Browse[1]>
> debug: y <- 1:5
> Browse[1]>
> debug: x <- "ABC"
> Browse[1]>
> debug: Sweave("test.rnw", driver = RweaveHTML)
> Browse[1]> x
> [1] "ABC"
> Browse[1]> y
> [1] 1 2 3 4 5
> Browse[1]>
> Writing to file test.html
> Processing code chunks ...
> 1 : term html
> 
> Error:  chunk 1
> Error in print(y) : object "y" not found
>> undebug(f1)
>>
>>   y <- 1:5
>>   x <- "ABC"
>>
>>
>> ls()
> [1] "f1" "x"  "y"
>>   Sweave("test.rnw", driver=RweaveHTML)
> Writing to file test.html
> Processing code chunks ...
> 1 : term html
> file  test.html is completed
> 
>> R.Version()
> $platform
> [1] "i386-pc-mingw32"
> 
> $arch
> [1] "i386"
> 
> $os
> [1] "mingw32"
> 
> $system
> [1] "i386, mingw32"
> 
> $status
> [1] ""
> 
> $major
> [1] "2"
> 
> $minor
> [1] "5.0"
> 
> $year
> [1] "2007"
> 
> $month
> [1] "04"
> 
> $day
> [1] "23"
> 
> $`svn rev`
> [1] "41293"
> 
> $language
> [1] "R"
> 
> $version.string
> [1] "R version 2.5.0 (2007-04-23)"
> 
> 
> ______________________________________________
> R-help at stat.math.ethz.ch mailing list
> https://stat.ethz.ch/mailman/listinfo/r-help
> PLEASE do read the posting guide http://www.R-project.org/posting-guide.html
> and provide commented, minimal, self-contained, reproducible code.



More information about the R-help mailing list