ryszard.czerminski@pharma.novartis.com
2003-Oct-31 19:39 UTC
[R] strange sprintf() behaviour ?
This is quite strange behaviour - at least for R-novice as myself.... Consider this:> testf <- function() { x <-2; sprintf("%s %f", "x =", x); return(x) } > result <- testf() > testf <- function() { x <-2; sprintf("%s %f", "x =", x) } > result <- testf() > testf()[1] "x = 2.000000" Apparently adding return() statement and invoking function like this "result <- testf()" suppresses output from sprintf() Output from print() is NOT suppressed:> testf <- function() { x <-2; print(c("x =", x)) } > result <- testf()[1] "x =" "2"> testf <- function() { x <-2; print(c("x =", x)); return(x) } > result <- testf()[1] "x =" "2" Is there a way to use sprintf() inside a function ? I guess I can say: print(sprintf()) - is it the only solution for this ? R [[alternative HTML version deleted]]
Hi, sprintf() returns a character string ('s' for string). See ?sprintf. It does not print (to standard output as you think). If you call it at the R prompt you'll get a string, which is then printed. Thus, to print it you should call cat(sprintf(...)) or print(sprintf(...)). About you previous question about %d and %f etc; If x is a double, %d can be used with as.integer(x) and %.0f with x to output as an integer. /Henrik> -----Original Message----- > From: r-help-bounces at stat.math.ethz.ch > [mailto:r-help-bounces at stat.math.ethz.ch] On Behalf Of > ryszard.czerminski at pharma.novartis.com > Sent: den 31 oktober 2003 20:39 > To: rossini at u.washington.edu > Cc: R help list; Bill Shipley; r-help-bounces at stat.math.ethz.ch > Subject: [R] strange sprintf() behaviour ? > > > This is quite strange behaviour - at least for R-novice as myself.... > > Consider this: > > > testf <- function() { x <-2; sprintf("%s %f", "x =", x); > return(x) } > > result <- testf() testf <- function() { x <-2; sprintf("%s > %f", "x =", > > x) } result <- testf() > > testf() > [1] "x = 2.000000" > > Apparently adding return() statement and invoking function like this > "result <- testf()" > suppresses output from sprintf() > > Output from print() is NOT suppressed: > > > testf <- function() { x <-2; print(c("x =", x)) } > > result <- testf() > [1] "x =" "2" > > testf <- function() { x <-2; print(c("x =", x)); return(x) > } result <- > > testf() > [1] "x =" "2" > > Is there a way to use sprintf() inside a function ? > > I guess I can say: print(sprintf()) - is it the only solution > for this ? > > R > > [[alternative HTML version deleted]] > > ______________________________________________ > R-help at stat.math.ethz.ch mailing list > https://www.stat.math.ethz.ch/mailma> n/listinfo/r-help > >