像 \Sexpr{} 中的 "and" 一样打印向量

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

考虑这个简单的向量:

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

\Sexpr{x} 将在 LaTeX 1,2,3,4,5 中打印,但我经常需要将文本中的一些矢量报告为人类,包括最后一个数字之前的 "and"。

我尝试使用此功能自动执行:

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)

这似乎在控制台中有效 \Sexpr{nicevector(x)} 但在 .Rnw 文件中却惨遭失败(而 \Sexpr{x} 有效)。一些想法?

您可以使用 knitr::combine_words(x).

使用cat()只是为了它的副作用:在控制台打印。 cat() 不会 return 一个字符串,所以你不会在输出中看到任何东西。相比之下,knitr::combine_words() return是一个字符串。

glue

中也有此功能
glue::glue_collapse(1:4, ",", last = " and ")
#> 1, 2, 3 and 4

help of function