I have an object one
that contains the results of a kruskal-wallis test. The p-value is really tiny i.e. 6.86e-09. Is there a way in inline code in R markdown to say p < 0.0001 instead of writing the exact p-value?
one <- kruskal.test(Petal.Width ~ Species, data = iris)
I have tried:
There was a statistically significant difference in the Petal Width between species
H(`r one[[2]]`) = `r round(one[[1]], 3)`, *p* = `r round(one[[3]], 11)`.
And:
`r if(one[[3]] < 0.0001){ print("< 0.0001") } else { round(one[[3]], 4) }`
Desired output:
There was a statistically significant difference in the Petal Width between species H(2) = 131.19, p < 0.0001.
There are lot's out there on how to recode into significance codes etc, but not really how to do this for inline code. I am new to this so any help is appreciated!
CodePudding user response:
You can use format.pval()
to format p-values.
format.pval(one$p.value, eps = 0.0001, scientific = FALSE)
# [1] "< 0.0001"
where eps
is a threshold; those less than eps
are formatted as "< [eps]"
(where [eps]
stands for format(eps, digits)
).
CodePudding user response:
You can use a vectorised ifelse
for this. If the value is smaller than 0.0001, print a "<" symbol together with 0.0001, else print a "=" symbol with the actual rounded value.
An addition one[[2]]
is included to demonstrate the case where the value is greater than 0.0001.
You can add an extra ifelse
statement at the beginning of your sentence (ifelse(one[[3]] < 0.0001, "was", "wasn't")
) to determine whether it is statistically significant or not.
---
title: "Untitled"
output: pdf_document
date: "2023-01-10"
---
```{r}
one <- kruskal.test(Petal.Width ~ Species, data = iris)
```
There `r ifelse(one[[3]] < 0.0001, "was", "wasn't")` a statistically significant difference in the Petal Width between species H(`r one[[2]]`) = `r round(one[[1]], 3)`, p `r ifelse(one[[3]] < 0.0001, paste("<", 0.0001), paste("=", round(one[[3]], 4)))`.
There `r ifelse(one[[2]] < 0.0001, "was", "wasn't")` a statistically significant difference in the Petal Width between species H(`r one[[2]]`) = `r round(one[[1]], 3)`, p `r ifelse(one[[2]] < 0.0001, paste("<", 0.0001), paste("=", round(one[[2]], 4)))`.
Rmarkdown PDF output example:
CodePudding user response:
For one, the print statement is probably unnecessary. On my end, it helped splitting the ifelse out of the inline, writing its result to a variable, and then just calling on that variable in the inline
one <- kruskal.test(Petal.Width ~ Species, data = iris)
pval <- if(one[[3]] < 0.0001){"< 0.0001"}else{round(one[[3]], 4)}
There was a statistically significant difference in the Petal Width between species H(`r one[[2]]`) = `r round(one[[1]], 3)`, p = `r pval`.
If you only have two conditions you can also use ifelse -
pval <- ifelse(one[[3]] < 0.0001, "< 0.0001", round(one[[3]],4))