Reputation: 264
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?
Upvotes: 2
Views: 625
Reputation: 6542
There is also a function for this in glue
package
glue::glue_collapse(1:4, ",", last = " and ")
#> 1, 2, 3 and 4
See help of function
Upvotes: 2
Reputation: 30114
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.
Upvotes: 2