how to use _sprintf_ and _for_ in R programming

半腔热情 提交于 2020-06-28 03:57:13

问题


I'm a beginner in R programming. I'm trying to use a for loop with the sprintf function. Without the for loop the function works pretty well:

var=2
sprintf("I want to print this number: %d",var)

The output:

"I want to print this number: 2"

Oddly for me, when I use for I don't have any outputs:

for (var in 1:10)
{
  sprintf('I want to print this number: %d', var)
}

Why is this happening? is there another function which can make this for me?


回答1:


You need to wrap it in cat():

for (var in 1:10)
{
  cat(sprintf('I want to print this number: %d', var), "\n")
}

I want to print this number: 1 
I want to print this number: 2 
I want to print this number: 3 
I want to print this number: 4 
I want to print this number: 5 
I want to print this number: 6 
I want to print this number: 7 
I want to print this number: 8 
I want to print this number: 9 
I want to print this number: 10

From help("sprintf"):

Value

A character vector of length that of the longest input.

So sprintf() is returning a character vector, not printing one. Outside a loop, returning the vector will print it in many contexts. However, in a context such as a loop, that's insufficient, you also need to tell R to display the returned vector in the console via, e.g., cat().



来源:https://stackoverflow.com/questions/62360803/how-to-use-sprintf-and-for-in-r-programming

标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!