user105833
user105833

Reputation: 39

How do I highlight certain words in a text, produced from a code chunkt?

I have text blocks that are stored in a table, I want to Output them as a markdown pdf and highlight certain words in it. Stuff like "Data" or "Science".

I found that I can use \textcolor{red}{red} to produce a red text in the document. However, this does not work, when code chunks provide the Basis for the text. How do I do this?


title: "Example" author: "" date: "20 5 2019"

output: pdf_document

knitr::opts_chunk$set(echo = TRUE)
library(tidyverse)

this works : Roses are \textcolor{red}{red}

mytext <- "I have a very important message"

mytext2 <- str_replace_all(mytext,"have","\textcolor{have}{red}")
mytext3 <- str_replace_all(mytext,"have","\\textcolor{have}{red}")



r mytext2 r mytext3

only produces:

I extcolor{have}{red} a very important message I textcolor{have}{red} a very important message

Upvotes: 1

Views: 426

Answers (1)

Martin Schmelzer
Martin Schmelzer

Reputation: 23909

Try

gsub("have","\\\\textcolor{red}{have}", mytext) 

It makes no difference if you use gsub or str_replace_all. The important change is to use 4 backslashes. And you have to change the argument order for textcolor.

Upvotes: 1

Related Questions