Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to check if the value is numeric?

Can someone help me modify the function below to check if a number is numeric?

# handy function that checks if something is numeric
check.numeric <- function(N){
  !length(grep("[^[:digit:]]", as.character(N)))
}

check.numeric(3243)
#TRUE
check.numeric("sdds")
#FALSE
check.numeric(3.14)
#FALSE

I want check.numeric() to return TRUE when it's a decimal like 3.14.

like image 444
user1313954 Avatar asked Nov 27 '22 21:11

user1313954


1 Answers

You could use is.finite to test whether the value is numeric and non-NA. This will work for numeric, integer, and complex values (if both real/imaginary parts are finite).

> is.finite(NA)
[1] FALSE
> is.finite(NaN)
[1] FALSE
> is.finite(Inf)
[1] FALSE
> is.finite(1L)
[1] TRUE
> is.finite(1.0)
[1] TRUE
> is.finite("A")
[1] FALSE
> is.finite(pi)
[1] TRUE
> is.finite(1+0i)
[1] TRUE
like image 154
Joshua Ulrich Avatar answered Dec 05 '22 23:12

Joshua Ulrich