问题
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