Search code examples
rknitrsweave

print vector as with "and" in \Sexpr{}


Consider this simple vector:

x <- c(1,2,3,4,5) 

\Sexpr{x} will print in LaTeX 1,2,3,4,5 but I often I need to report some vectors in text as a human, including "and" before the last number.

I tried todo automatically with this function:

x <- c(1,2,3,4,5)
nicevector <- function(x){
    a <- head(x,length(x)-1)
    b <- tail(x,1)
    cat(a,sep=", ");cat(" and ");cat(b)}
nicevector(x)

That seem to work in the console \Sexpr{nicevector(x)} but failed miserably in the .Rnw file (while \Sexpr{x} works). Some ideas?


Solution

  • You can use knitr::combine_words(x).

    Using cat() is only for its side-effect: printing in the console. cat() won't return a character string, so you won't see anything in the output. By comparison, knitr::combine_words() returns a character string.