I need to insert the species names in a table created by xtable in my Rnw file and I want to convert the relative column to italics format. Is it possible without any manual intervention?
My call is:
xtable(cklist, caption="Checklist...", align='lllc',label = 'tab:ckzygo')
To typeset a column in italics (or any other non-standard font shape), you should use the >{\cmd} syntax for column specification.
Assigning the column type >{\itshape}l generates a left-justified column in italics.
This is a better solution than iris$Species <- paste0("\\textit{", iris$Species, "}") as suggested in the comments because you neither have to modify your data nor you need to disable text sanitizing.
Small illustration:
\documentclass{article}
\usepackage{array}
\begin{document}
<<xtableItalics, results = "asis">>=
library(xtable)
print(xtable(head(iris), align = c(rep("l", 5), ">{\\itshape}l")))
#
\end{document}
The PDF looks like:
Please note that you need to use the array package for this to work.
EDIT: To show the flexibility of this approach, two more examples:
print(xtable(head(iris), align = c(rep("l", 5), ">{\\textit\\bgroup}l<{\\egroup}")))
print(xtable(head(iris), align = c(rep("l", 5), ">{\\textcolor{red}\\bgroup}l<{\\egroup}")))
The first line uses \textit{} instead of \itshape to typeset the italics. As \textit{} requires the text to modify as an argument, we need a slightly more complex syntax. (It's described in the wikibooks.org article linked above.)
This syntax can also be used to change for example the color of the text. In more complex cases, lrbox is required, as described in the linked article.
Related
I am using xtable and want my column names to containt a . The reason is, that I want to copy this into Latex and have Special symbols avaible. I have tried this:
names(xt) = c("$\\kappa$", "$\\theta$")
print(xt, math.style.exponents = TRUE)
but my names read \$$\backslash$kappa\$. This is nice because in Latex it translates to exactly what I wrote. But I want special characters, so it's not so nice for me. Can I somehow print the titles literally, or something similar?
print(xt, math.style.exponents = TRUE, sanitize.text.function=function(x){x})
As pointed out in the comments, this argument needs to be added so that the sanitization doesn't mess the titles up.
I am trying to include links to particular webpages in a 'kable' table in Rmarkdown, when creating a pdf.
The table has 4 columns, and I wish for the links to be in the second column, which currently includes strings. The output of the table is given below;
knitr::kable(ind_rank_table_final,row.names = FALSE,caption = "Industry Rank",align = rep("l",ncol(ind_rank_table)))
Using paste0, you can construct markdown-formatted URLs in your dataframe, and then pass that to kable, like so:
---
output: pdf_document
---
```{r}
# some urls
urls <- rep("https://stackoverflow.com/", 10)
# use paste0 to compose markdown-formatted hyperlinks
mtcars$mpg <- paste0("[", mtcars$mpg, "](", urls, ")")
# print the table, with hyperlinked text
knitr::kable(head(mtcars))
```
And you can see the result, blue text in the mpg column, and if I hover my mouse over, I see the URL:
If you want to print the URLs in the table, and have them clickable, then you'de do something like this mtcars$mpg <- paste0("[", urls, "](", urls, ")") like so:
Is that what you're after? This use of paste0 is pretty handy for doing all sorts of things to tables, for example, combining multiple values in one cell, and applying conditional formatting (like bold for significant values)
For those knitting to PDFs using bookdown, #Ben's answer will not get you fully the way there. As #mavericks pointed out, you will still see the full text ([21](https://stackoverflow.com/), to keep with #maverick's example).
To fix this, add the argument format = "pipe" or format = "simple" to kable(). The "latex" option, while generating a working link, will display like #maverick's example. The default behavior for kable() is to automatically determine the format, which I guess in the case of a bookdown document must be "latex"?
I don't know, but this should generate #Ben's first table for bookdown users:
output: bookdown::pdf_document2
# some urls
urls <- rep("https://stackoverflow.com/", 10)
# use paste0 to compose markdown-formatted hyperlinks
mtcars$mpg <- paste0("[", mtcars$mpg, "](", urls, ")")
# print the table, with hyperlinked text
knitr::kable(head(mtcars), format = "simple")
I am using knitr for a report wherein I have a lot of inline output text, mostly numeric values, using \Sexpr{}. I want to highlight All these inline outputs in my generated pdf.
Example code:
\documentclass[12pt]{article}
\begin{document}
<<echo=FALSE, include=FALSE>>=
N <- 100 # Total
N_f <- 60 # Women
#
There were \Sexpr{N} people in the company, \Sexpr{N_f} women and \Sexpr{N - N_f} men.
\end{document}
Hence, in the output all the number should be highlighted, i.e. with a shaded background (similar to using with \hl{} with the \usepackage{soul}).
It seems to me that the solution would use one of the inline output hooks. Another possibility might be to write a LaTeX function which search all the \Sexpr{...} expressions in the entire document and highlights them in the generated pdf. I am still learning and can not figure out how to implement these.
Thanks for any help or hints.
Note: The knitr page by yihui talks about manipulation of the numeric value (scientific notation, digits after decimal points) which I have got covered.
The output hook inline can be used to style output from \Sexpr{}. This is as simple as
knit_hooks$set(inline = function(x) { sprintf("\\textbf{%s}", x)})
Just define an arbitrary function that takes an argument x and returns the string to be printed. In this example I used \textbf to make the output bold, but this can be extended to any LaTeX commands.
In this answer, Yihui suggests an improvement that still takes the default inline hook into account. This ensures rounding as usually performed by the default hook:
hook_inline <- knit_hooks$get('inline')
knit_hooks$set(inline = function(x) { sprintf("\\textbf{%s}", hook_inline(x))})
I would like to keep the width of columns I set using align argument of xtable and I would like to align all numeric columns to the right, others to the left and the headers to the center.
I found some solutions using tables which are written directly in the rnw file but I want to load my data from file because my table is quite big and can change during creation of the knitr document.
The code (I used the iris dataset in this example instead of my own data):
<<table_symbionts_chunk, results="asis", echo=FALSE>>=
library(xtable)
irisX <-print (xtable (iris,
digits=rep(0,6),
align= c("p{0.015\\textwidth}|",
"p{0.37\\textwidth}|",
"p{0.12\\textwidth}|",
"p{0.08\\textwidth}|",
"p{0.02\\textwidth}|",
"p{0.35\\textwidth}|")))
#
The tricky part of this question refers to LaTeX. Please not that my TeX code is based on these two questions on tex.stackexchange:
How to create fixed width table columns with text raggedright/centered/raggedleft?
Center column with specifying width in table (tabular enviroment)?
One part of the question is easy to answer: How to set a fixed column width but align all numeric columns right and all other columns left?
This is only a matter of correct column types (see the answers linked above). A solution could be:
\documentclass{article}
\usepackage{array}
\newcolumntype{R}[1]{>{\raggedleft\let\newline\\\arraybackslash\hspace{0pt}}p{#1}}
\begin{document}
<<table_symbionts_chunk, results="asis", echo=FALSE>>=
library(xtable)
irisShort <- head(iris)
print(xtable(irisShort,
digits=rep(0,6),
align=c(
"p{0.015\\textwidth}|",
"R{0.37\\textwidth}|",
"R{0.12\\textwidth}|",
"R{0.08\\textwidth}|",
"R{0.02\\textwidth}|",
"p{0.35\\textwidth}|")))
#
\end{document}
As p{} columns are left justified by default we only need to define one new column type for right justified columns with a fixed width: R.
Note that the column names overlap but this is due to the widths specified in the question.
Centering the column names requires a different justifications for the first row only. This can be achieved using the \multicolumn command. However, as we want to add LaTeX code to the column names, we moreover have to prevent xtable from sanitizing the column names using sanitize.colnames.function = identity:
irisShort2 <- irisShort
colnames(irisShort2) <- paste("\\multicolumn{1}{c|}{", colnames(irisShort2), "}")
print(xtable(irisShort2,
digits=rep(0,6),
align=c(
"p{0.015\\textwidth}|",
"R{0.37\\textwidth}|",
"R{0.12\\textwidth}|",
"R{0.08\\textwidth}|",
"R{0.02\\textwidth}|",
"p{0.35\\textwidth}|")),
sanitize.colnames.function = identity)
paste("\\multicolumn{1}{c|}{", colnames(irisShort2), "}") uses the original column names but encloses them in \multicolumn{1}{c|}{colname} which provides centered column names.
Note that now to column names do not overlap anymore (instead, the table is too wide) because of the changed column type in the first row.
The two code snippets in this answer produce the following output:
I was having the same problem, and want to share this works in R console as
library(xtable)
irisShort <- head(iris)
print(xtable(irisShort,
digits=rep(0,6),
align=c(
"p{1cm}|","p{3cm}|",
"p{2cm}|","p{3cm}|",
"p{3cm}|","p{3cm}|")))
In the knitr package I like the kable function. It gives a nice layout of tables and data frame like objects even as it is called from within an R code chunk. Now I want to do the same thing with a character value. Is there a function that gives a kable-like output ("kprint") that can be formated?
knitr::kable() # exists for tables
knitr::kprint() # does a function like this exists for character values?
This is what I get now:
print("character value") # within the R Chunk
Output in generated report:
## [1] "character value"
And this is what I want, just:
character value
EDIT cat("character value") is not the solution I am looking for because I don't want an R output anymore, but just a plain text.
There are two things to do to get a "raw" character string (without any formatting or additional output like [1]) from R to TEX:
Use the chunk option results = "asis" to instruct knitr not to modify the output.
Use cat instead of print because print adds the lenght of the vector and quotes to the output.
In this context, inline output using \Sexpr{} might be useful because values in \Sexpr{} are by default printed "as they are": \Sexpr{myoutput}.
As there was the question of how to format the output in the comments, here some options:
Add LaTeX to the text you pass to cat: cat("\\emph{foo}"). Don't forget to escape \ by an additional \.
Do the same thing as above, but use a function to do the "dirty work":
makeItNiceR <- function(x) {
return(paste("\\fbox{\\texttt{", x, "}}"))
}
cat(makeItNiceR("foo bar is nice"))
(Note that we could use cat inside makeItNiceR to save some typing, but this makes the function less flexible and we cannot use it in combination with \Sexpr{} anymore.)
Manually add LaTeX formatting commands around \Sexpr{}:
Add formatting to \emph{\Sexpr{myoutput}} directly in LaTeX.
Combine makeItNiceR and \Sexpr{} to get nicely formatted output from \Sexpr{}:
\Sexpr{makeItNiceR(paste(myoutput, "is nice"))}
The following minimal examples demonstrates the usage of all code snippets from above:
\documentclass{article}
\begin{document}
<<results = "asis">>=
makeItNiceR <- function(x) {
return(paste("\\fbox{\\texttt{", x, "}}"))
}
myoutput <- "slim"
cat("foo")
cat("\\emph{foo}")
cat(makeItNiceR("foo bar is nice"))
#
\paragraph{Outside of chunk:} ~\\
\Sexpr{myoutput} \\
Add formatting to \emph{\Sexpr{myoutput}} directly in LaTeX. \\
\Sexpr{makeItNiceR(paste(myoutput, "is nice"))}
\end{document}