suppose I want to print a list of variables in my markdown file and I want to highlight them from the rest of the text using code style. For example using the names of the iris data
The variable names of the iris data set are `r paste0(names(iris), collapse = ", ")`
should return
The variable names of the iris data set are Sepal.Length, Sepal.Width, Petal.Length, Petal.Width, Species
However, if I use this approach and try to include backticks inside the inline code with e.g.
The variable names of the iris data set are `r paste0(paste0("`", names(iris), "`"), collapse = ", ")`
or any version of trying to escape the backtick character that I could come up with ended with an error message.
Ok... After experimenting a bit I came up with a pretty close solution to what I was looking for:
backticks around the inline code
The variable names of the iris data set are ``r paste0(names(iris), collapse = ", ")``
Related
I am trying to include a table in Rmarkdown that it looks like in Word. This is how I have the table in Word:
Is there a way that I can include this table exactly as the image in a Rmardown document?
Get a screenshot of the table from the document and use
![Caption for the picture.](/path/to/your/folder/imagename.png)
If we want to create a table from a model object use gtsummary or flextable
library(gtsummary)
library(flextable)
data(trial)
model <- glm(response ~ trt, trial, family = binomial)
tbl_regression(model)
as_flextable(model)
Based on the format showed, crosstable would also work
library(crosstable)
crosstable(ggplot2::mpg, class, by = drv) %>%
crosstable::as_flextable()
this is a big problem for me as I need to have un-named column names inside my flextable in officer. This previously worked with the ReporteRs version.
But so far haven't been able to do this, tried using the following code:
rename(` ` = col0)
When I run try and create a flextable using this column name I get the following error message:
Error in flextable(a) :
invalid col_keys, flextable support only syntactic names
data <- head(iris) %>%
rename(` ` = Sepal.Length)
myft <- regulartable(data)
myft1<- flextable(data)
Note: the regulartable(data) works and the column name is blank.
When trying to do this with a flextable however it doesn't work and errors
Is there anyway that I am able to do this with a flextable?
Many thanks in advance
You don't need to modify your data.frame to customize the display. Having names like is risky IHMO. Read https://davidgohel.github.io/flextable/articles/layout.html#manage-headers-and-footers
library(flextable)
library(magrittr)
library(dplyr)
data <- head(iris)
myft <- regulartable(data) %>%
set_header_labels(Sepal.Length = " ")
myft1 <- flextable(data) %>%
set_header_labels(Sepal.Length = " ")
myft1
My data frame has ugly column names, but when displaying the table in my report, I want to their "real" names including special characters '(', new lines, greek letters, repeated names, etc.
Is there an easy way of replacing the names in knitr to allow such formatting?
Proposed solution
What I have tried to do is suppress the printing of the data frame names and use add_header_above for better names and names that span several columns. Some advice I've seen says to use:
x <- kable(df)
gsub("<thead>.*</thead>", "", x)
to remove the column names. That's fine, but the issue is that when I subsequently add_header_above, the original column names come back. If I use col.names=rep('',times=ncol(d.df)) in kable(...) the names are gone but the row remains, leaving a gap between my new column names and the table body. Here's a code chunk to illustrate:
```{r functions,echo=T}
drawTable <- function(d.df,caption='Given',hdr.above){
require(knitr)
require(kableExtra)
require(dplyr)
hdr.2 <- rep(c('Value','Rank'),times=ncol(d.df)/2)
x <- knitr::kable(d.df,format='latex',align='c',
col.names=rep('',times=ncol(d.df))) %>%
kable_styling(bootstrap_options=c('striped','hover',
'condensed','responsive'),position='center',
font_size = 9,full_width=F)
x %>% add_header_above(hdr.2) %>%
add_header_above(hdr.above)
}
```
```{r}
df <- data.frame(A=c(1,2),B=c(4,2),C=c(3,4),D=c(8,7))
hdr.above <- c('A2','B2','C2','D2')
drawTable(df,hdr.above = hdr.above)
```
I am not sure where you got the advice to replace rownames, but it seems excessively complex. It is much easier just to use the built-in col.names argument within kable. This solution works for both HTML and LaTeX outputs:
---
output:
pdf_document: default
html_document: default
---
```{r functions,echo=T}
require(knitr)
df <- data.frame(A=c(1,2),B=c(4,2),C=c(3,4),D=c(8,7))
knitr::kable(df,
col.names = c("Space in name",
"(Special Characters)",
"$\\delta{m}_1$",
"Space in name"))
```
PDF output:
HTML output:
If you're targeting HTML, then Δ is an option too.
I couldn't get the accepted answer to work on HTML, so used the above.
I have the following dataframe:
site_name | site_url
--------------------| ------------------------------------
3D Printing | https://3dprinting.stackexchange.com
Academia | https://academia.stackexchange.com
Amateur Radio | https://ham.stackexchange.com
I want to generate a third column with the link integrated with the text. In HTML I came up with the following pseudo code:
df$url_name <- "[content of site_name](content of site_url)"
resulting in the following working program code:
if (knitr::is_html_output()) {
df <- df %>% dplyr::mutate(url_name = paste0("[", df[[1]], "](", df[[2]], ")"))
knitr::kable(df)
}
Is there a way to this in LaTeX with knitr as well?
(I am preferring a solution compatible with kableExtra, but if this is not possible I am ready to learn whatever table package can do this.)
*** ADDED: I just noticed that the above code works within a normal .Rmd document with the yaml header output: pdf_document. But not in my bookdown project.
The problem is with knitr::kable. It doesn't recognize that the bookdown project needs Markdown output, so you need to tell it that explicitly:
df <- df %>% dplyr::mutate(url_name = paste0("[", df[[1]], "](", df[[2]], ")"))
knitr::kable(df, format = "markdown")
This will work for any kind of Markdown output: html_document, pdf_document, bookdown::pdf_book, etc.
Alternatively, if you need LaTeX output for some other part of the table, you could write the LaTeX equivalent. This won't work for HTML output, of course, but should be okay for the PDF targets:
df <- df %>% dplyr::mutate(urlName = paste0("\\href{", df[[2]], "}{", df[[1]], "}"))
knitr::kable(df, format = "latex", escape = FALSE)
For this one I had to change the column name; underscores are special in LaTeX. You could probably get away without doing that if you left it as format = "markdown", but then you'd probably be better off using the first solution.
I'm using R Sweave and wanted to begin my document with showing a sample of my table. My problem is, that my table has 39 variables and many rows. For the rows it isn't a problem, I can take only a few ones using sample_n, but I need to habe all my variables visible. It would sadly not fit either on a landscape sheet. I'm using xtable to generate my table. I think the easier way would be to put so much variables as possible on the sheet, then begin with the rest under, and so on, until it is all displayed.
Here some minimalist exemple:
dat <- bind_cols(mtcars, mtcars, mtcars, mtcars)
a <- as.data.frame(dat) %>%
sample_n(5)
print(xtable(a))
I've already know the longtable function, but it would only help me if I had too much rows, and not too much columns, isn't it? I'm still a little bit lost with having at the same time R and LaTeX on the same file...
An answer using my huxtable package. Create the table, then break it up by columns:
library(huxtable)
dat <- sample_n(as.data.frame(bind_cols(mtcars, mtcars, mtcars, mtcars)), 5)
ht <- as_hux(dat, add_colnames = TRUE)
# now format to taste:
bold(ht)[1,] <- TRUE
ht[,1:5] # first 5 columns. Will print as LaTeX within a Rmarkdown document