Max Ghenis
Max Ghenis

Reputation: 15803

Vectorize digits arg to format() in R

I'd like to format a vector of numbers with a dynamic number of digits, as specified in another vector. format only uses the first element of the digits vector though. Is there any way to vectorize this?

Example:

format(c(0.15, 0.43), digits=c(1, 2)) 
# [1] "0.1" "0.4" 
# Expected: c("0.1", "0.43")

Upvotes: 0

Views: 60

Answers (2)

Max Ghenis
Max Ghenis

Reputation: 15803

Per akrun:

mapply(format, c(0.15, 0.43), digits=c(1,2))
#[1] "0.1" "0.43"

While this is probably slower than Richard Scriven's sprintf recommendation, it works better for me because I'm using other parts of format less suitable to sprintf, like the thousands separator.

Upvotes: 0

Rich Scriven
Rich Scriven

Reputation: 99331

Instead of format(), you could do it with sprintf()

sprintf("%2$.*1$g", c(1, 2), c(0.15, 0.43))
# [1] "0.1"  "0.43"

This is based on one of the examples shown in ?sprintf

n <- 1:6
## Asterisk and argument re-use, 'e' example reiterated:
sprintf("e with %1$2d digits = %2$.*1$g", n, exp(1))
# [1] "e with  1 digits = 3"       "e with  2 digits = 2.7"    
# [3] "e with  3 digits = 2.72"    "e with  4 digits = 2.718"  
# [5] "e with  5 digits = 2.7183"  "e with  6 digits = 2.71828"

Upvotes: 2

Related Questions