R语言简单循环未在控制台输出结果的问题咨询
Hey there! I see the issue with your code—let's fix it quickly.
The problem is that sprintf() only creates a formatted string; it doesn't automatically print that string to the console. In R, when you run a single expression interactively, it prints the result by default, but inside a for loop, you have to explicitly tell R to output the text.
Here are a few easy solutions:
1. Use print() with sprintf()
Wrap your sprintf() call in print() to send the formatted string to the console:
it = 10:110 for(i in it) { print(sprintf("partial r2 for iteration %f is %f....", i, 0.0)) }
2. Use cat() for cleaner output (no quotes/brackets)
If you want to avoid the default quotes and brackets that print() adds, use cat() instead. Add a \n at the end to make each output line break properly:
it = 10:110 for(i in it) { cat(sprintf("partial r2 for iteration %f is %f....\n", i, 0.0)) }
3. Use message() for status-style output
If you're using this to log progress, message() is a good choice—it's designed for informative messages and won't interfere with other output:
it = 10:110 for(i in it) { message(sprintf("partial r2 for iteration %f is %f....", i, 0.0)) }
Any of these should make your loop output visible in the RStudio console right away!
内容的提问来源于stack exchange,提问作者Luckylukee

