简体   繁体   中英

Formatted scientific names from R to LaTeX (using Sweave or knitr)

I am implementing a function print_name in the package taxlist . For example, I can format a name for markdown:

library(taxlist)
data(Easplist)
print_name(Easplist, 206, style="markdown")

The output in the console is then:

[1] "*Cyperus papyrus* L."

I can use this command for example to mention a species in the content of a markdown document by `r I(print_name(Easplist, 206, style="markdown"))` , where the scientific name appears as italics and the author name does not.

I would like to implement an option (ie style="latex" ) retrieving the string formatted for LaTeX, which can be inserted through something like \\Sexpr{print_name(Easplist, 206, style="latex")} (this example is only an hypothetical one). The output should be then \\textit{Cyperus papyrus} L. but all my attempts failed because backslash is a scape in R strings.

Is there a way to achieve properly this task?

Note: The function is at the moment not implemented in the CRAN version of the package, thus to reproduce the example use the last version from GitHub:

devtools::install_github("kamapu/taxlist")

What I imagine that you are doing is this:

<<example, echo=FALSE>>=
library(taxlist)
data(Easplist)
\Sexpr{print_name(Easplist, 206, style="markdown")}
@

Simply move the \\Sexpr{} to outsite the chunk.

<<example, echo=FALSE>>=
library(taxlist)
data(Easplist)
@

\Sexpr{print_name(Easplist, 206, style="markdown")}

That will output you what you want.

EDIT:

If you are trying to incorporate "latex" as a style option for the output, then it should look like this when it outputs outside of latex:

library(taxlist)
data(Easplist)
print_name(Easplist, 206, style="latex")
[1] "\\textit{Cyperus papyrus} L."

The "\\" will escape the escape. I did not incorporate it into your function, but here is an example:

<<>>=
example_text <- "Cyperus papyrus L."
example_text <- strsplit(example_text, split = " ")
test1 <- paste0("\\textit{", example_text[[1]][1], " ", example_text[[1]][2], "}", 
            " ", example_text[[1]][3])
@

\Sexpr{test1} is a paper reed. 

The output looks like this in the rendered pdf.

在此处输入图片说明

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM