alittleboy
alittleboy

Reputation: 10956

calculate the number of digits in a numeric vector in R

I have a vector of numeric in R:

 c(0.9, 0.81)

and I'd like to extract the number of digits for each element in this vector. The command will return, in this case, 1 and 2 since the digits are 9 and 81. Is there a convenient way to do it? Also, if the result is 1, how can I expand to two digits? For example, I'd like a returned vector to be

 c(0.90, 0.81)

Upvotes: 6

Views: 12981

Answers (2)

bgoldst
bgoldst

Reputation: 35314

x <- c(0.9,0.81,32.52,0);
nchar(sub('^0+','',sub('\\.','',x)));
## [1] 1 2 4 0

This strips the decimal point, then strips all leading zeroes, and finally uses the string length as an indirect means of computing the number of significant digits. It naturally returns zero for a zero input, but you can use an if expression to explicitly test for that case and return one instead, if you prefer.

As akrun mentioned, for printing with two digits after the decimal:

sprintf('%.2f',x);
## [1] "0.90"  "0.81"  "32.52" "0.00"

Upvotes: 5

Rorschach
Rorschach

Reputation: 32426

To count the digits after the decimal, you can use nchar

sapply(v, nchar) - 2  # -2 for "." and leading 0
# 1 2

Upvotes: 8

Related Questions