Rotate column headers on Hmisc generated table - r

I need to rotate the headers from a table 90 degrees using the Hmisc package. I tried changing the 'colnamesTexCmd' command but nothing changes on the column headers.
Below is a reproducible example of my problem
---
title: ""
author: ""
date: "November 20, 2015"
header-includes:
- \usepackage{longtable, colortbl, xcolor, lscape, rotating, ctable}
output: rmarkdown::tufte_handout
---
```{r tableDescStatTest, results ='asis', echo=FALSE, message = FALSE, warning = FALSE, include=TRUE}
library(Hmisc)
data(iris)
DescTableTest <- summary(Species ~ Sepal.Length + Sepal.Width,
data = iris,
method = "reverse",
test = T,
continuous = 0)
# fuction to take the first row of comment from the latex output
mylatex <- function (...) {
o <- capture.output(latex(...))
# this will strip /all/ line-only comments; or if you're only
# interested in stripping the first such comment you could
# adjust accordingly
o <- grep('^%', o, inv=T, value=T)
cat(o, sep='\n')
}
# render the table
options(digits = 1)
mylatex(DescTableTest,
exclude1 = FALSE,
colnamesTexCmd = "rotatebox{90}",
npct = 'numerator',
npct.size = "footnotesize",
what = c('%'),
landscape = FALSE,
file = "",
long = T,
middle.bold = TRUE,
longtable = FALSE,
overall = TRUE,
label = "tbl:descTable1",
prmsd = FALSE,
caption = "Descriptive statistics",
caption.loc = 'bottom',
where = "!htbp")
```

You are using the S3 latex method for class summary.formula.reverse
? Hmisc::summary.formula
which does not take the argument colnamesTexCmd

Related

How to suppress downloading progress in HTML file

I am using imfr package to download some IMF data series
library(imfr)
t <- imf_data(database_id = "BOP", indicator = "BCA_BP6_USD",
country = "all", start = "1990", freq = "Q")
I prespecified certain parameters in a separate chunk before to suppress downloading progress
knitr::opts_chunk$set(echo = FALSE, message = FALSE, warning = FALSE, error = FALSE, results = 'hide', fig.keep = 'all')
However, neither of these options did the job. Moreover results = 'hide' suppressed all the output including text and figures.
How can I solve this issue without having a separate chunk for data downloading?
You can capture all those downloads message and progress bar in capture.output and wrap it with invisible. (Got this idea from this question and answer on SO).
And then make a wrapper function imf_data which works the same (mask the imfr::imf_data function) but does not print all those download messages and the progress bar.
---
title: "IMF Data"
output: html_document
---
```{r setup, include=FALSE}
knitr::opts_chunk$set(echo = TRUE, warning = FALSE, message = FALSE)
imf_data <- function(...) {
invisible(capture.output(dt <- imfr::imf_data(...)))
return(dt)
}
```
```{r}
library(imfr)
t <- imf_data(database_id = "BOP", indicator = "BCA_BP6_USD",
country = "all", start = "1990", freq = "Q")
```
```{r, comment=""}
head(t)
```

Programmatically create a question_text with multiple answers in r learnr:tutorial

I have the following code with 4 correct answers. I want the students to input all 4 of them. Instead of defining 24 permutations of the answers, I want 4 field boxes that would only accept an answer once.
question_text(
"Input all paths:",
answer("ABEF", correct = TRUE),
answer("ABCDG", correct = TRUE),
answer("ABCDEF",correct = TRUE),
answer("ABDEF", correct = TRUE),
incorrect = "Direction from top to bottom of the plate",
allow_retry = TRUE,
trim = TRUE
)
EDIT
I tried this approach but I do not think I can set the answer as anything other than a single text:
library(gtools)
pat <- permutations(4, 4, c("ABEF","ABCDG","ABCDEF","ABDEF"))
question_text(
"Input all possible rupture paths:",
answer(pat, correct = TRUE),
allow_retry = TRUE,
trim = TRUE
)
Even if I set pat <- c("ABEF","ABCDG","ABCDEF","ABDEF") it does not run successfully. How can define multiple answers at the same time without writing them out.
I'm not sure about your desired output - however, please check the following.
Referring to:
How can define multiple answers at the same time without writing them
out.
You can use lapply to create the answers and do.call to pass the different arguments to question_text:
library(learnr)
do.call(question_text, c(
list("Input all paths:"),
lapply(c("ABEF", "ABCDG", "ABCDEF", "ABDEF"), answer, correct = TRUE),
list(
incorrect = "Direction from top to bottom of the plate",
allow_retry = TRUE,
trim = TRUE
)
))
as *.Rmd file:
---
title: "Tutorial"
output: learnr::tutorial
runtime: shiny_prerendered
---
```{r setup, include=FALSE}
library(learnr)
knitr::opts_chunk$set(echo = FALSE)
```
```{r two-plus-two, exercise=FALSE}
do.call(question_text, c(
list("Input all paths:"),
lapply(c("ABEF", "ABCDG", "ABCDEF", "ABDEF"), answer, correct = TRUE),
list(
incorrect = "Direction from top to bottom of the plate",
allow_retry = TRUE,
trim = TRUE
)
))
```
Regarding:
I want 4 field boxes that would only accept an answer once
Edit: Added an event handler to access to the answers provided by the user.
---
title: "Tutorial"
output: learnr::tutorial
runtime: shiny_prerendered
---
```{r setup, include=FALSE}
library(learnr)
knitr::opts_chunk$set(echo = FALSE)
questions <-
mapply(
FUN = question_text,
lapply(c("ABEF", "ABCDG", "ABCDEF", "ABDEF"), answer, correct = TRUE),
text = paste("Question", 1:4),
incorrect = paste("Incorrect", 1:4),
MoreArgs = list(allow_retry = TRUE,
trim = TRUE),
SIMPLIFY = FALSE
)
```
```{r q1, echo = FALSE}
do.call(quiz, c(list(caption = "Quiz 1"), questions))
```
```{r context="server-start"}
event_register_handler("question_submission", function(session, event, data) {
# names(data):
# "label" "question" "answer" "correct"
message("event: question_submission: ", data$answer)
})
```

R Markdown inline Code inside Latex math-environment

short question, I've got this Code
```{r,include=F}
ct <- export2latex(createTable(compareGroups (grade ~ age ,
data = dat, max.ylev = 10, max.xlev = 20), show.p.overall = F, show.all = TRUE, sd.type = 2))
and I'm using an inline code in R-markdown knitr like the following
$ `r ct` $
My problem now is that that I can't get rid of the dollar signs in my printed pdf which looks like this.
Does anybody know how to get rid of the dollar signs in my text?
Here is a MRE
---
title: "Test"
author: "Author"
date: "24 2 2020"
output: pdf_document
---
```{r setup, include=FALSE}
knitr::opts_chunk$set(echo = TRUE)
library(compareGroups)
n1 <- rnorm(10)
n2 <- rnorm(10,1,1)
dat <- data.frame(PID = 1:20,value = c(n1,n2), group = rep(1:2,each = 10))
ct <- export2latex(createTable(compareGroups (group ~ value, data = dat, max.ylev = 10, max.xlev = 20), show.p.overall = F, show.all = TRUE, sd.type = 2))
Now here should be displayed the table one
$r ct$.
But the dollar signs are still in the document.
Seccond try with other math enviroment
\(r ct\).

rmarkdown resize plot inside of code chunk

I have an rmarkdownfile with a chunck that has a loop that creates many pages. Below is a toy example. See the "loop_chunk" code chunk. The "loop_chunk" has fig.width=9, fig.height=6, results="asis" and I am running into a problem where i need to reduce the size of a plot inside loop_chunk. All plots are 9x6 but I need to adjust one plot. I found the codee below: http://michaeljw.com/blog/post/subchunkify/
and I tried using it below but when you run the code you can see that there are 2 plots on pages 3 and 5 and there should not be. it is somehow not keeping the \newpages. There should be 1 plot on pages 2,3,4 and 5. There should only be 5 pages.
Any idea how to fix this?
---
title: "Untitled"
output: pdf_document
toc: yes
---
```{r setup, include=FALSE}
knitr::opts_chunk$set(echo = FALSE , comment = NA, message= FALSE, warning = TRUE)
subchunkify <- function(g, fig_height=7, fig_width=5) {
g_deparsed <- paste0(deparse(
function() {g}
), collapse = '')
sub_chunk <- paste0("
`","``{r sub_chunk_", floor(runif(1) * 10000), ", fig.height=", fig_height, ", fig.width=", fig_width, ", echo=FALSE}",
"\n(",
g_deparsed
, ")()",
"\n`","``
")
cat(knitr::knit(text = knitr::knit_expand(text = sub_chunk), quiet = TRUE))
}
data = data.frame(group= c("A","A"), value = c(1,3))
```
```{r loop_chunk, fig.width=9, fig.height=6, results="asis", message= FALSE, warning = FALSE}
for(i in 1:nrow(data)){
cat(paste0("\\newpage\n # Page ", i ," \n"))
plot(data$value[i])
cat("\n\n")
cat(paste0("\\newpage\n ## page with smaller plot \n\n"))
cat("Here is some text on this page for the smaller plot.")
cat("\n\n")
data2 = data.frame(x = 7, y = 900)
library(ggplot2)
myplot = ggplot(data2, aes(x = x, y = y ))+geom_point()
subchunkify(myplot , 4,4 )
# print(myplot) -> IS there a way to just reduce the height and width with print()?
cat("\n\n")
}
```
Using your subchunkify() function for the graphics::plot call outputs those plots to the intended pages. Replacing plot(data$value[i]) in your second chunk with
subchunkify(plot(data$value[i]), 5, 5)
outputs the 5 pages with plots as intended (where height & width are set to 5/can be edited to conditionally set dimensions for a specific plot).

Suppress alt text for GIFs in rmarkdown HTML output

I'm generating GIFs using the gganimate package within an RMarkdown file. When using output = github_document in the front matter, the GIF appears as expected in the output (github-document-output). However, when using output = html_document, the GIF generates with alt text, which defaults to the chunk name (html-document-output).
Is there a way to suppress this automatic caption? I've tried setting my own caption using the fig.cap chunk option, but that was unsuccessful.
RMarkdown code
---
output:
html_document: default
github_document: default
---
```{r}
knitr::opts_chunk$set(
collapse = TRUE,
comment = "#>",
fig.path = "output/test-fig-",
cache.path = "output/test-cache-"
)
```
```{r cache = FALSE}
library(knitr)
library(animation)
ani.options(autobrowse = FALSE, interval = 1)
opts_knit$set(animation.fun = function(x, options, format = "gif") {
x = c(knitr:::sans_ext(x), knitr:::file_ext(x))
fig.num = options$fig.num
format = sub("^[.]", "", format)
fig.fname = paste0(sub(paste0(fig.num, "$"), "*", x[1]),
".", x[2])
mov.fname = paste0(sub(paste0(fig.num, "$"), "", x[1]), ".",
format)
# order correctly
figs <- Sys.glob(fig.fname)
figs <- figs[order(as.numeric(stringr::str_match(figs, paste0("(\\d+)\\.", x[2]))[, 2]))]
animation::im.convert(figs, output = mov.fname)
sprintf("![%s](%s)", options$label, paste0(opts_knit$get("base.url"), mov.fname))
})
opts_chunk$set(cache = TRUE, message = FALSE, warning = FALSE, fig.show = "animate")
```
```{r pkgs, cache = FALSE}
library(gapminder)
library(ggplot2)
theme_set(theme_bw())
```
```{r setup}
p <- ggplot(gapminder, aes(gdpPercap, lifeExp, size = pop, color = continent, frame = year)) +
geom_point() +
scale_x_log10()
```
```{r dependson = "setup"}
library(gganimate)
gg_animate(p)
```
The problem here is that you include the resulting animation with markdown syntax. This introduces some iiritations I guess.
Taking a look at hook_plot_html we can simulate the default output for standard plots:
sprintf(paste0('<div class="figure %s">',
'<img src="%s">',
'<p class="caption">%s</p>',
'</div>'), options$fig.align, mov.fname, options$fig.cap)

Resources