2

Using knitr, I want to sort \items based on a sorted vector of their values in R. So in the example below, I want the bullets to be printed in numeric order based on df$value, not in alphabetical order as they exist now. How can get LaTeX to rearrange them for me?

\documentclass{article}
\begin{document}

<<echo = FALSE, message = FALSE>>=
library(dplyr)
a = 1; b = 3; c = 4; d = 2
df = data.frame(name = c('a', 'b', 'c', 'd'), value = c(1, 3, 4, 2))
order = arrange(df, value)$name
@

\begin{itemize}
% some code here to rearrange based on \Sexpr{order}...
    \item \Sexpr{a} is the first letter of the alphabet.
    \item \Sexpr{b} is the first letter in "build".
    \item \Sexpr{c} is a decent grade.
    \item \Sexpr{d} stands for dog.
\end{itemize}

\end{document}

One point that is important here is that merely calling \item \Sexpr{order[1]} is not sufficient because the other text in each \item has to be rearranged too.

0
2

Knirt cannot modify the containing LaTeX code. Therefore, you must make the whole list in R. For example, you can make a R vector of the sorted strings, then add \item to each element and show as LaTeX code with the results="asis" option.

enter image description here

\documentclass{article}
\usepackage[T1]{fontenc}
\usepackage[utf8]{inputenc}
\usepackage{fmtcount}
\begin{document}
R dataframe:
<<echo=F,results='asis',message=F>>=
require(xtable)
df = data.frame(name = c("a","b","c","d"), value = c(1, 3, 4, 2),
comment=c(
  "is the first letter of the alphabet.",
  'is the first letter in “build”.',
  "is a decent grade.",
  "stands for dog."))
xtable(df,digits=0)
@
List of comments in \LaTeX\ by ordered value:
<<echo=F,results='asis'>>=
odf = df[with(df, order(value)), ]
cat("\\begin{itemize}\\item")
cat(paste("\\ordinalnum{",odf$value,
"} (\\texttt{",odf$name,"}) ",odf$comment, sep=""), sep="\n\\item ")
cat("\\end{itemize}")
@
\end{document}

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

Not the answer you're looking for? Browse other questions tagged or ask your own question.