Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

calculate the number of digits in a numeric vector in R

Tags:

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)
like image 433
alittleboy Avatar asked Aug 08 '15 14:08

alittleboy


People also ask

How do you find the number of digits in a number?

The proof generalizes to compute the number of digits required to represent a number in any base. For example, the number n=1234 written in base 2 requires k = ceil(log2(n+1)) = 11 digits. You can check that the 11-digit binary number 10011010010 equals the decimal value 1234.


2 Answers

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

sapply(v, nchar) - 2  # -2 for "." and leading 0
# 1 2
like image 126
Rorschach Avatar answered Nov 06 '22 18:11

Rorschach


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"
like image 24
bgoldst Avatar answered Nov 06 '22 17:11

bgoldst