使用 cat 打印出向量的所有值的 R 方法是什么?

What is the R way to print out all values of a vector using cat?

出于格式化目的,我想使用 cat() 打印出数组的值。

我可以使用 for 循环轻松地做到这一点...但我想以 "right" 的方式做到这一点。

randNums <- rnorm(5)
for(i in randNums){
  cat("n")
  cat(",")
  cat(i)
  cat("\n")
}

输出:

n,-0.06339912
n,1.276653
n,0.1581441
n,-1.347136
n,1.777113

"right way",我的意思是使用应用函数之一而不是 for 循环。

你可以试试

cat(paste(seq_along(randNums), randNums,sep=",", collapse="\n"), '\n')

如果你需要'n'

cat(paste('n', randNums,sep=",", collapse="\n"), '\n')

要获得准确的输出形式,请使用 "n," 和值:

> cat(paste("n", randNums,sep=",", collapse="\n"), '\n')
n,-0.135970405811417
n,2.19536614784033
n,0.567067477368411
n,1.97238205385431
n,-0.34726999999616 

使用 apply-family 函数会导致这种混乱:

> invisible(lapply(randNums,function(x){cat("n,",x,"\n",sep="")}))
n,1.56346
n,1.360061
n,2.048337
n,0.234013
n,0.1050811