Search code examples
rlatexsweave

using source("X.R") in Sweave file


I need to use a function in my Sweave file to execute chunk codes. For example, I have function MEAN <- function(x) mean(x) in my directory, then I want use the chunk code

x=c(1,2,3,4)
MEAN(x)

in my Sweave file. Does anyone know how can I do that?

Thanks.


Solution

  • When you are writing code normally inside the code blocks of the document, just make sure to set the directory of where the R file is located and source the file.

    e.g.,

    <<echo=TRUE>>=
        setwd(mydirectory)
        source(myfile)
        print(MEAN(x))
    @