首页 > 解决方案 > 使用 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

谢谢

标签: rcat

解决方案


稍微更通用(对于 的情况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

推荐阅读