Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Is there a vectorized way to use is.numeric?

I was reading this question at SO and was wondering if there is any way to use is.numeric in a vectorized way. The point being, if you have a vectorized way to check if a variable is numeric, then any function what depends on the variable being numeric can be vectorized. Otherwise, it cannot be vectorized.

like image 741
Manoel Galdino Avatar asked Jan 30 '12 14:01

Manoel Galdino


1 Answers

As per the comments:

if you're looking to test columns of a data.frame with as.numeric, use apply

> dat <- data.frame(v1=1:5,v2=letters[1:5],v3=rnorm(5),v4=c(1,2,'c','d',5))

> sapply(dat,is.numeric)
   v1    v2    v3    v4 
 TRUE FALSE  TRUE FALSE 

Or, for variety, you can use colwise from the plyr package:

> colwise(is.numeric)(dat)
    v1    v2   v3    v4
1 TRUE FALSE TRUE FALSE
like image 178
Justin Avatar answered Sep 18 '22 15:09

Justin