Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
403 views
in Technique[技术] by (71.8m points)

r - Count the number of integer digits

I want to count the number of digits before the decimal point for a numeric vector x with numbers greater or equal to 1. For example, if the vector is

x <- c(2.85, 356.01, 66.1, 210.0, 1445.11, 13.000)

my code should return a vector containing integers 1, 3, 2, 3, 4, 2

Does any know how to do this?

See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Answer

0 votes
by (71.8m points)

This is probably the best way (for positive numbers):

floor(log10(x)) + 1

If you want an answer that works for negative numbers too, add in an abs():

floor(log10(abs(x))) + 1

The log10 method will not work if the input is exactly 0, so if you want a robust solution with that method, handle 0 as a special case:

n_int_digits = function(x) {
  result = floor(log10(abs(x)))
  result[!is.finite(result)] = 0
  result
}

You can also use nchar(trunc(x)), but this seems to behave poorly for large numbers. It will also count leading 0s, whereas the log method will not.


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...