Like Matlab's sprintf
, R's sprintf
only creates a string, it doesn't print it to the output.* You have to explicitly call the print
function to see anything:
print(sprintf("%f", pi)) # prints
A plain sprintf
officially creates a string and then discards it because it wasn't saved to a variable:
sprintf("%f", pi) # does nothing
However, this sort of worked for you because the REPL (the command line that runs R code one line at a time) disobeys the directive to discard values that aren't saved to variables, but instead prints them. This is a convenience thing to make it easier to work at the command line. You can type 1+1
and get it to print 2
even though an R script would normally discard the value silently.
Other functions that print text to the console are cat
and message
, which are each slightly different. See their help files for usage.
* Technically, Matlab will print the value of any statement that isn't terminated by a ;
, including strings. So without a semicolon, the string that results from sprintf
can get printed though it's not being done by sprintf
directly, but by the generic print-all-the-things behavior of Matlab. In my opinion, this is a weird feature.