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?


<<echo = FALSE, message = FALSE>>=
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

% 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.


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.


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

R dataframe:
df = data.frame(name = c("a","b","c","d"), value = c(1, 3, 4, 2),
  "is the first letter of the alphabet.",
  'is the first letter in “build”.',
  "is a decent grade.",
  "stands for dog."))
List of comments in \LaTeX\ by ordered value:
odf = df[with(df, order(value)), ]
"} (\\texttt{",odf$name,"}) ",odf$comment, sep=""), sep="\n\\item ")

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.