Programming R/Sweave for proper \Sexpr output
- by deoksu
Hi I'm having a bit of a problem programming R for Sweave, and the #rstats twitter group often points here, so I thought I'd put this question to the SO crowd. I'm an analyst- not a programmer- so go easy on me my first post.
Here's the problem: I am drafting a survey report in Sweave with R and would like to report the marginal returns in line using \Sexpr{}. For example, rather than saying:
Only 14% of respondents said 'X'.
I want to write the report like this:
Only \Sexpr{p.mean(variable)}$\%$ of respondents said 'X'.
The problem is that Sweave() converts the results of the expression in \Sexpr{} to a character string, which means that the output from expression in R and the output that appears in my document are different. For example, above I use the function 'p.mean':
p.mean<- function (x) {options(digits=1)
mmm<-weighted.mean(x, weight=weight, na.rm=T)
print(100*mmm)
}
In R, the output looks like this:
p.mean(variable)
>14
but when I use \Sexpr{p.mean(variable)}, I get an unrounded character string (in this case: 13.5857142857143) in my document. I have tried to limit the output of my function to 'digits=1' in the global environment, in the function itself, and and in various commands. It only seems to contain what R prints, not the character transformation that is the result of the expression and which eventually prints in the LaTeX file.
as.character(p.mean(variable))
>[1] 14
>[1] "13.5857142857143"
Does anyone know what I can do to limit the digits printed in the LaTeX file, either by reprogramming the R function or with a setting in Sweave or \Sexpr{}? I'd greatly appreciate any help you can give.
Thanks,
David