Home > OS >  Extracting a p-value from a test in R
Extracting a p-value from a test in R

Time:11-27

I cannot seem to be able to extract a specific value from my code

df <- data.frame(x1 = rnorm(50),
                  x2 = 2*rnorm(50),
                  x3 = 3*runif(50)) 

shapiro.test(df$x1)

After this chunk, there's an output in the R-studio pane where I get a p-value in which I want to extract to my output file.

So my question is how I easily can extract that p-value using inline R-code.

CodePudding user response:

This is easy:

shapiro.test(df$x1)$p
[1] 0.6798121

CodePudding user response:

Here:

df <- data.frame(x1 = rnorm(50),
                 x2 = 2*rnorm(50),
                 x3 = 3*runif(50)) 

test<-shapiro.test(df$x1)
test$p.value

CodePudding user response:

First store your value inside your chunk

pvalue <- shapiro.test(df$x1)$p.value

Then write outside of the chunk

`r paste(pvalue)`

This will display your pvalue when you knit.
It is interesting because if your outcome changes, the text will also change.

If you need more cross-referencing:
https://bookdown.org/yihui/rmarkdown-cookbook/cross-ref.html

  • Related