使用 cat 输出向量元素序列

Output a sequence of vector element using cat

我需要使用 R 中的 cat 函数来获取某些输出语句。我编写了以下代码

it <-1
w <- c(1,2,3)
cat("\nUsing the eq(s)",w,"the iter is:",it,"\n",sep=",")

这给了我以下输出

Using the eq(s),1,2,3,the iter is:,1,

如果你能帮忙,我需要得到这个输出

Using the eq(s) 1, 2 and 3, the iter is: 1

谢谢

1) 纯猫这样试试:

cat("\nUsing the eq(s) ", toString(head(w, -1))," and ", tail(w, 1), 
  ", the iter is: ", it, "\n", sep = "")

给予:

Using the eq(s) 1, 2 and 3, the iter is: 1

1a) 此变体使用 toString,然后将最后一个逗号替换为 and。它的优点是即使 w 的长度为 1.

也能正常工作
cat("\nUsing the eq(s) ", sub("(.*),(.*)", "\1 and \2", toString(w)),
   ", the iter is: ", it, "\n", sep = "")

其余的解决方案也可以使用这个想法,但我们将仅将它们显示为 (1) 的变体。

2) sprintf 另一种方法是像这样使用 sprintf

s <- sprintf("\nUsing the eq(s) %s and %d, the iter is: %d\n", 
       toString(head(w, -1)), tail(w, 1), it)
cat(s)

3) fn$ 另一种方法是 gsubfn 中的 fn$。如果像 fn$f 那样在任何函数 f 前面加上它,那么将对参数进行字符串插值。

library(gsubfn)

fn$cat(
  "\nUsing the eq(s) `toString(head(w, -1))` and `tail(w, 1)`, the iter: is $it\n"
)

稍微更通用(对于 length(w) != 3 的情况):

enlist <- function(x) {
  n <- length(x)
  if (n <= 1) return(x)
  paste(toString(x[-n]), "and", x[n])
}

cat("Using the eq(s) ", enlist(w), ", the iter is: ", it, "\n", sep = "")
Using the eq(s) 1, 2 and 3, the iter is: 1