Search code examples
rfunctionlatexsweaveknitr

Function for mean and sem in Sweave/knitr implementation


I am brainstorming to write a mean and sem function for Sweave/knitr use. And for my limited knowledge it look like this

m.se <- function (x, na.rm = TRUE) {
    if (na.rm) 
        x <- x[!is.na(x)]
    n <- length(x)
    if (n == 0) 
        return(c(mean = NA, sem = NA))
     xbar <- sum(x)/n
     se <- sqrt(sum((x - xbar)^2)/(n - 1))/sqrt(n)
     c(mean = xbar, sem = se)
     return(paste(xbar,"\\pm",se))
}

It really does some job and it give output like:

43.9303846153846 \pm 3.34823050767781

The problem is it does not respect option() that I define in main environment (setup chunk in knitr). How can I solve this problem.


Solution

  • I think the format function will do the trick:

    R> 1.1111111
    [1] 1.111
    R> paste(1.1111111)
    [1] "1.1111111"
    R> paste(format(1.1111111))
    [1] "1.111"
    

    So in your case,

    paste(format(xbar), "\\pm", format(se))