Here’s a very simple way to include p-levels in Sweave. Let’s assume you want to mention a correlation coefficient in your text, `\Swexpr{}`

will do just that.

`\Sexpr{round(cor.test(x, y)$estimate,2)}`

You can easily include the p-level, too.

`\Sexpr{round(cor.test(x, y)$p.value,2)}`

Except that’s not how it’s usually done. Normally we report whether the p-value is smaller than a certain threshold, and by convention only a few of them are considered.

Enter a very simple function (I’d include this in my first Sweave block where I load the data):

plevel <- function (x, strict=FALSE) {
# levels of p-values, for Sweave
# strict cuts at 0.05, otherwise cuts at 0.1
if (x>0.1 & strict==FALSE) p <- "p>0.1" # not significant
if (x>0.1 & strict==TRUE) p <- "p>0.05" # not significant
if (x<=0.1 & strict==FALSE) p <- "p<0.1" # significant
if (x<=0.1 & strict==TRUE) p <- "p>0.05" # not significant
if (x<=0.01) p <- "p<0.01" # significant
if (x<=0.05) p <- "p<0.05" # significant
if (x<=0.001) p <- "p<0.001" # significant
return(p)
}

Created by Pretty R at inside-R.org

This automatizes the procedure, and the cited thresholds will always be correct. I could make this function simpler by leaving out the strict argument, or obviously adjust the thresholds.

So, here’s how I use this in Sweave: `some text ($r=\Sexpr{round(cor.test(x, y)$estimate,2)}$, $\Sexpr{plevel(cor.test(x, y)$p.value)}$) some more text`

.

The dollar signs (math mode) mean that I get nice typography for the numbers and operators.

### Like this:

Like Loading...

*Related*

Thanks for your explanation. I was looking for a simple way to deal with formatting _p_ values. I noticed, however, that your logic is off in your 4th _if_ statement. If

, it may or may not be significant. It depends! It still works because of your other statements, though.

I was working on simplifying your logic for my purposes and ended up refactoring the whole thing. Since it was your idea, I wanted to share. Hopefully it will give you an idea: https://github.com/myqlarson/r-library-misc/blob/master/format.R#L44

Thanks for your comment and sharing your code! You’re right that the statement in question is ambiguous, but — as you write — it is the later lines of code that fix this. I guess your code is more generic…