Printing in R studio with sprintf() does work, but not when inside a for loop?

Viewed 868

This works all the time when pasted into the command line separately withOUT for loop:

 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])

This does not print any output when run in the for loop from the script file... :

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()
}
1 Answers

The difference in print and sprintf is in the return value. According to ?sprintf

A wrapper for the C function sprintf, that returns a character vector containing a formatted combination of text and variable values.

where as in ?print

print prints its argument and returns it invisibly (via invisible(x)).

If we want to print in a for loop wrap the sprintf in a print or cat or 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()
}
Related