Output from mediate function in RMarkdown - r

Im trying to inculde the output of the mediate function from mediation package in my RMarkdown (PDF) document. Using summary it gives me the table with the results from the bootstrapping analysis when I knitr the RMarkdown to a PDF document, but:
I don't like the look of the output and wuld like to have a more shiny table.
I can't lable this table with a caption and it's not included in the autmatic nummeration of RMarkdown (and as a consequence I can't reference it in the text).
I tried to use kable or xtabs with the output of the 'mediate` function but it won't work since both functions don't accept the class ("summary.mediate" "mediate") of the output.
This is how the code chunk in my RMarkdown document loks like:
```{r med.y1.z6.z7.c, echo = F, comment = "", strip.white = T, fig.cap="test"}
regDFM <- na.omit(as.data.frame(cbind(Y1, X1, Z1, Z6, Z7)))
regFIT1.C.medY <- lm(Y1 ~ X1+Z1+Z6+Z7+X1:Z1, data = regDFM)
regFIT1.C.medM <- lm(Z7 ~ X1+Z1+Z6+X1:Z1, data = regDFM)
fitMED <- mediation::mediate(regFIT1.C.medM, regFIT1.C.medY,
boot = T, sims = 10, treat="Z6", mediator="Z7")
summary(fitMED)
```
Any help or ideas are very appreciated!

With kable and the elements of the mediate function I finally created a nice RMarkdown > PDF output.
First I created a data.frame using the relevant elements of the mediate function (are the called 'elements'? what would yu call them?). Then just passing the data.frame to kable.
Thanks to #henrik_ibsen for the hint.
Here is my code:
regDFM <- na.omit(as.data.frame(cbind(Y1, X1, Z1, Z6, Z7)))
regFIT1.C.medY <- lm(Y1 ~ X1+Z1+Z6+Z7+X1:Z1, data = regDFM)
regFIT1.C.medM <- lm(Z7 ~ X1+Z1+Z6+X1:Z1, data = regDFM)
fitMED <- mediation::mediate(regFIT1.C.medM, regFIT1.C.medY,
boot = T, sims = 10, treat="Z6", mediator="Z7")
bt_effect <- c("Indirekter Effekt", "Direkter Effekt", "Gesamt Effekt",
"Anteil direkter Effekt")
bt_est <- c(fitMED$d1, fitMED$z1, fitMED$tau.coef, fitMED$n1)
#bt_p <- format.pval(c(fitMED$d1.p, fitMED$z1.p, fitMED$tau.p, fitMED$n1.p))
bt_p <- c(fitMED$d1.p, fitMED$z1.p, fitMED$tau.p, fitMED$n1.p)
bt_stars <- c(stars.pval(fitMED$d1.p), stars.pval(fitMED$z1.p),
stars.pval(fitMED$tau.p), stars.pval(fitMED$n1.p))
bt_DF <- data.frame(row.names = bt_effect, format(bt_est, digits = 2),
format(bt_p, nsmall = 3), bt_stars)
colnames(bt_DF) <- c("Koeffizienten", "p-Werte", "")
kable(bt_DF, booktabs = T, align = "c",
caption = "Bootstraping-Analyse für Mediation") %>%
footnote(general = c("Simulationen: 1000", "Signifikanzniveaus: ∗ p<0.05;
∗∗ p<0.01; ∗∗∗ p<0.001"),
general_title = "Anmerkungen:")

Related

Conditionally display math formulas with variables in R Markdown

I have a problem with rendering formulas with variables in R markdown.
Here is the variables that I using (simple example):
```{r, include=FALSE}
series <- c(1, 2, 3, 4)
count <- leng(series)
sum <- sum(series)
sum2 <- sum(series^2)
sq_formula <- TRUE
My problem is to print in Rmd (output = Word) math expression with knitr like:
$$S = \frac{\sum{S}}{n} = \frac{`r sum`}{`r count`} = `r mean(series)`$$
if sq_formula is FALSE, otherwise it should be:
$$S = \frac{\sum{S^2}}{n} = \frac{`r sum2`}{`r count`} = `r sum2 / count`$$
There is a way to write formulas in R chunk and print it by condition, like:
```{r, include=FALSE}
formula1 <- '$$ \\overline{S} = \\frac{\\sum{S}}{n} = \\frac{\\sum{`r sum`}{`r count`}}$$'
formula2 <- '$$ \\overline{S} = \\frac{\\sum{S^2}}{n} = \\frac {\\sum{`r sum2`}}{`r count`}$$'
`r if (sq_formula <- TRUE) {formula1} else {formula2}`
but I can't insert the variables like r sum, r count inside the chunk.
I also tried to handle the problem with sprintf function, but haven't found a way to insert the variables in strings in math notation. So I would be grateful for any help.
What is the problem with sprintf? Can't you do
formula1 <- sprintf(
'$$ \\overline{S} = \\frac{\\sum{S}}{n} = \\frac{\\sum{%s}{%s}}$$',
sum, count
)

knitr: how to print the visible parts of the expression in a custom code chunk using engine_output()?

I am creating a custom code chunk which rewrites the expressions that a user passes into the code block into valid R code, and then execute the analysis. Aside from the rewriting of the R expression that the user inputs, the goal is for the code chunk to work as a regular code chunk
I then execute the result and store it in a variable, which I am trying to output. I am running into two issues here:
It prints invisible variables
knit_print and engine_output do not seem to work with each other i.e. I want the output such as dataframes to be printed in the table format but I am not able to get it to work.
An example of what I am trying to do would be something like:
```{r}
custom_engine <- function(options) {
c = options$code
pasted <- paste(c, collapse = "\n")
code <- parse(text = pasted)
result = lapply(code, eval, envir = .GlobalEnv)
knit_print(result)
engine_output( options, code = c, out = NULL )
}
knitr::knit_engines$set(mmm = custom_engine)
```
```{r}
speed_data <- data.frame(
speed = rlnorm(100, log(200), 1),
device = sample(c("smartphone", "laptop", "tablet"), 100, TRUE, prob= c(0.1, 0.65, 0.25))
)
median = median(speed_data$speed)
iqr = IQR(speed_data$speed, na.rm=TRUE)
```
```{mmm}
result_analysis <- speed_data %>%
filter(speed < median + 3 * iqr & speed > 10) %>%
filter(device != "smartphone")
result_analysis
```
I would like the code above to print the table once, and in the default knit_print() format that RMarkdown does.
Any suggestions would be much appreciated.

cloze question does not display questions?

I'm having trouble writing a cloze question with the exams package in R. I tried to stick close to the boxhist.Rmd example, but something must be wrong. the weird thing is that knitting the Rmd in rstudio displays all components ok - it's just that the html output is blank for the questions? any ideas much appreciated! here is my Rmd file, that I give to exams:::exams2html:
```{r data generation, echo = FALSE, results = "hide"}
m = sample(c(-1,0,5),1)
s = sample(c(1,10,20))
x = rnorm(mean = m, sd = s, n = 100)
write.csv(x, file="sumstats.csv",quote = FALSE,row.names = FALSE)
questions <- rep(list(""), 5)
solutions <- rep(list(""), 5)
explanations <- rep(list(""), 5)
type <- rep(list("num"),5)
questions[[1]] <- "What is the Interquartile range of $x$?"
questions[[2]] <- "What is the Variance of $x$?"
questions[[3]] <- "What is the standard deviation of $x$?"
questions[[4]] <- c("The standard deviation is *always* smaller than the variance.","The standard deviation is *NOT always* smaller than the variance.")
questions[[5]] <- "What is the median of $x$?"
solutions[[1]] <- round(IQR(x),3)
solutions[[2]] <- round(var(x),3)
solutions[[3]] <- round(sd(x) ,3)
solutions[[4]] <- mchoice2string(c(FALSE,TRUE))
solutions[[5]] <- round(median(x),3)
type[[4]] <- "schoice"
explanations[[1]] <- "Function `IQR`"
explanations[[2]] <- "Use `var(x)`"
explanations[[3]] <- "`sd(x)`"
explanations[[4]] <- "$\\sqrt{x}$ is not always smaller than $x$. Try $x=0.5$!"
explanations[[5]] <- "`median(x)`"
```
```{r questionlist, echo = FALSE, results = "asis"}
answerlist(unlist(questions), markup = "markdown")
```
Solution
========
```{r solutionlist, echo = FALSE, results = "asis"}
answerlist(paste(unlist(explanations), ".", sep = ""), markup = "markdown")
```
Meta-information
================
extype: cloze
exsolution: `r paste(solutions, collapse = "|")`
exclozetype: `r paste(type, collapse = "|")`
exname: sumstats
extol: 0.05
You omitted the
Question
========
markup before the question list. Actually, I'm surprised that this works at all, given that R/exams does not know where the question is...
Also, the length of the unlisted questions (6) needs to match the length of the unlisted solutions (currently only 5). This may be necessary in some learning management systems to provide feedback on the individual sub-items.

merge columns every other row using Sweave/R/Latex

I am writing a conference abstract booklet using R/Sweave. I have already made the program booklet for printing that contains the id, author, title only.
Now I want to modify it to include the abstract (not for print). But abstracts are lengthy. My thought is to take the cell with the abstract info, and have it display below the row with the author info - expanded across the full width of the page.
ID--author--------title--------------------------------
abstract-----------------------------------------------
So every other row has only one column spanning the width of the entire table.
Is there a way to add multicolmn{x} to every other row?
If a solution can't be figured out, advice for how to print full abstracts in a nice way would be welcome. (Something other than "just use landscape" or "adjust column widths")
Also, it doesn't have to be PDF. I could switch to markdown/html - and make it look closer to real conference program schedules that have full abstracts on them. Again, one I figure out how to print a table where every other row has only one column that is the width of the entire table.
If you want to try - Here is a complete MWE for what I have working now. Note that it uses the R package lipsum which has to be installed via devtools/github.
\documentclass{article}
\usepackage{booktabs, multicol, array}
\usepackage[margin=0.75in]{geometry}
%%%%%%%%%%% Let tables to span entire page
\newcolumntype{L}[1]{>{\raggedright\let\newline\\\arraybackslash\hspace{0pt}}m{#1}}
<<echo=FALSE, warning=FALSE, message=FALSE>>=
# devtools::install_github("coolbutuseless/lipsum")
library(lipsum)
library(xtable)
knitr::opts_chunk$set(echo = FALSE, warning=FALSE, message=FALSE)
options(xtable.comment = FALSE)
tblalign <- "lL{0.5cm}|L{4cm}L{6cm}L{8cm}"
# fake data setup
dat <- data.frame(ID = c(1:3), author = substr(lipsum[1:3], 1, 40),
title = substr(lipsum[4:6], 1, 100),
abstract = lipsum[7:9])
names(dat)=c("\\multicolumn{1}{c}{\\textbf{\\large{ID}}}",
"\\multicolumn{1}{c}{\\textbf{\\large{Author List}}}",
"\\multicolumn{1}{c}{\\textbf{\\large{Title}}}",
"\\multicolumn{1}{c}{\\textbf{\\large{Abstract}}}")
#
\begin{document}
<<results='asis'>>=
print(
xtable(x = dat
, align = tblalign)
, table.placement = "H"
, sanitize.colnames.function=function(x){x}
, include.rownames = FALSE
, include.colnames = TRUE
, size = "small"
, floating = FALSE
, hline.after = c(0,1:nrow(dat))
)
#
\end{document}
Split data from abstract manually
out <- dat[,-4]
ab.list <- dat$abstract
then add.to.row
, add.to.row = list(pos = as.list(1:nrow(out)),
command = paste0("\\multicolumn{3}{L{15cm}}{\\textbf{Abstract: }", ab.list, "} \\\\"))
One approach using my package huxtable. I couldn't install lipsum for some reason, so just hacked it. This is in a .Rmd file with output pdf_document.
```{r, results = 'asis'}
lipsum <- rep(do.call(paste, list(rep('blah ', 100), collapse = '')), 10)
dat <- data.frame(ID = c(1:3), author = substr(lipsum[1:3], 1, 40),
title = substr(lipsum[4:6], 1, 100),
abstract = lipsum[7:9], stringsAsFactors = FALSE)
library(huxtable)
# shape data
datmat <- matrix(NA_character_, nrow(dat) * 2, 3)
datmat[seq(1, nrow(datmat), 2), ] <- as.matrix(dat[, c('ID', 'author', 'title')])
datmat[seq(2, nrow(datmat), 2), 1] <- dat$abstract
# print as PDF
ht <- as_huxtable(datmat)
colspan(ht)[seq(2, nrow(ht), 2), 1] <- 3
wrap(ht) <- TRUE
col_width(ht) <- c(.2, .2, .6)
number_format(ht) <- 0
ht
```

How can I subscript names in a table from kable()?

Given a data.frame A, how can I use subscripted rows and columns names? Eventually I want produce a table through kable() in rmarkdown (output: word document).
A <- data.frame(round(replicate(3, runif(2)),2))
rownames(A) <- c("Hola123", "Hola234")
A
X1 X2 X3
Hola123 0.47 0.55 0.66
Hola234 0.89 0.45 0.20
How could I make all numbers from row and column names subscripted when creating a table through kable(A)?
I have tried:
rownames(A) <- c(expression(Hola["123"]), expression(Hola["234"]))
names(A) <- c(expression(X["1"]), expression(X["2"]), expression(X["3"]))
But it does not appears subscripted when creating the table through kable() in the .rmd file.
To add subscripts in a rmarkdown document, you can embed your text between two tilde: text~sub~.
When using function kable, any text in the table is recognized as markdown syntax. So that your rmarkdown code should be:
```{r}
A <- data.frame(round(replicate(3, runif(2)),2))
rownames(A) <- c("Hola~123~", "Hola~234~")
names(A) <- c("X~1~", "X~2~", "X~3~")
knitr::kable(A)
```
Just one note about bamphe's response is that the correct code is misspelled. It should be \\textsubscript{}. It is missing the second "t".
And completing the answer, you might choose to use the arguments row.names and col.names inside kable, in this way:
A <- data.frame(round(replicate(3, runif(2)),2))
rownames(A) <- c("Hola\\textsubscript{123}", "Hola\\textsubscript{234}")
knitr::kable(A,
row.names = T,
col.names = c("X\\textsubscript{1}", "X\\textsubscript{2}", "X\\textsubscript{3}"),
escape = F)
I, too, was looking for a method that would allow for subscript and superscript in both html and pdf formats in markdown tables with kable. After a bit of searching, I finally found the text reference method explained here by #yihui-xie : bookdownguide
(ref:foo) H~2~O where foo is the reference and H~2~O the text.
My code example shows how the text reference can be used. Make sure to follow the cardinal rules:
The reference needs to be unique throughout the document
The reference should not have a white space following the "to be inserted stuff"
The reference needs to be in its own paragraph and have an empty line both above and below it
Note that only the referenced "foo" and "fo" will give the subscripts while the ~[]~ method will only work in html but not pdf.
(ref:foo) CO~2~/CO~2~
(ref:fo) CO~2~
```{r chunk-to-show-the-text-reference-method, echo = FALSE }
library(dplyr)
library(knitr)
library(kableExtra)
# Make lists
dtmin_name <- c("ref/ref","refrigerant/CO2","(ref:foo)",paste0("ground/","(ref:fo)"),"ground/water","air/refrigerant","water/refrigerant","water/CO2")
temp_diff <- c( 2.3, 1.4, 0.8, 6.8, 14, 6, 4, 3.46)
# Make dataframe and column names
dtmin_df <- data.frame(dtmin_name,temp_diff, stringsAsFactors = FALSE)
colnames <- data.frame("Interface Type ", "dT~min~ Interval [K]", stringsAsFactors = FALSE)
colnames(dtmin_df) <- colnames
# Make Table
kable(dtmin_df, caption = "Typical dT~min~ Temperature Intervals", booktabs = TRUE, format.args = list(big.mark = ",")) %>%
kable_styling(bootstrap_options = c("striped", "hover"),latex_options = c("striped","scale_down"))```

Resources