在 R studio 中使用 sprintf() 进行打印确实有效,但在 for 循环内则无效?

bab*_*lon 6 r

当单独粘贴到命令行而不使用 for 循环时,这始终有效:

 sprintf("Your maximum allowed investment for a period of %g years in the first year equals  %g", current_nr_of_years, max_invest_year_zero_vec[current_nr_of_years])
Run Code Online (Sandbox Code Playgroud)

在脚本文件的 for 循环中运行时,不会打印任何输出...:

loop_index_vec
for (current_nr_of_years in loop_index_vec) {
  
  sprintf("Your maximum allowed investment for a period of %g years in the first year equals  %g", current_nr_of_years, max_invest_year_zero_vec[current_nr_of_years])
  # browser()
}
Run Code Online (Sandbox Code Playgroud)

akr*_*run 6

print和的区别sprintf在于return价值。根据?sprintf

C 函数 sprintf 的包装器,返回包含文本和变量值的格式化组合的字符向量。

哪里如?print

print 打印它的参数并以不可见的方式返回它(通过invisible(x))。

如果我们想print在 for 循环中将 包裹sprintfprintorcat或 中message

for (current_nr_of_years in loop_index_vec) {
  
  print(sprintf("Your maximum allowed investment for a period of %g years in the first year equals  %g", current_nr_of_years, max_invest_year_zero_vec[current_nr_of_years]))
  # browser()
}
Run Code Online (Sandbox Code Playgroud)