Using percent symbol (%) with sprintf

Viewed 839

Consider the example

n <- 100    
for (j in 1:n) {
    print(sprintf("Processing feature %i from %i; %1.0f",j,n,j/n*100))
}

But I would like to have an output text with a "%" at the end of each line, just like

Processing feature 15 from 100; 15%

Of course

n <- 100    
for (j in 1:n) {
    print(sprintf("Processing feature %i from %i; %1.0f%",j,n,j/n*100))
}

returns error message because the last "%"

How can I can get the percent symbol "%" at the end of the output string using sprintf command?

Thanks in advance

1 Answers

1) Use a double percent. (See ?sprintf for all the percent codes.)

j <- 2; n <- 3
sprintf("Processing feature %i of %i (%.0f%%)", j, n, 100 * j / n)
## [1] "Processing feature 2 of 3 (67%)"

1a) or rounding the last one so that we can use %i for it too:

sprintf("Processing feature %i of %i (%i%%)", j, n, round(100 * j / n))
## [1] "Processing feature 2 of 3 (67%)"

2) If we preface print (or any function) with fn$ from gsubfn then we can use $ to refer to a variable (provided it only contains word characters and the end of it is delimited by a non-word character) and backquotes to contain R code.

library(gsubfn)

fn$print("Processing feature $j of $n (`round(100*j/n)`%)")
[1] "Processing feature 2 of 3 (67)%"
Related