[R] Printing linefeeds using sprintf
Hedderik van Rijn
hedderik at cmu.edu
Wed Aug 13 03:33:28 CEST 2003
> Is there a way to print complex, multi-line text and numeric output
> with
> good control of the field width and precision of numeric values? In
> the
> first example in the R Documentation for the sprintf function, there
> appears
> to be a linefeed code "\n", but it is printed literally.
>
>> sprintf("%s is %f feet tall\n", "Sven", 7)
> [1] "Sven is 7.000000 feet tall\n"
That is because the output of sprintf is the _string_ that sprintf
returns. You could cat this string to get the behavior you probably
expected:
> cat(sprintcat(sprintf("%s is %f feet tall\n\nNew line\n", "Sven", 7))
Sven is 7.000000 feet tall
New line
>
The following code defines a C-like "printf":
printf <- function(...) { cat(sprintf(...)) }
> printf("%s is %f feet tall\n", "Sven", 7)
Sven is 7.000000 feet tall
>
- Hedderik.
More information about the R-help
mailing list