Search code examples
rvectorization

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.


Solution

  • As per the comments:

    if you're looking to test columns of a data.frame with as.numeric, use sapply or lapply (but not 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:

    library(dplyr)  # since pkg:plyr is now deprecated
    colwise(is.numeric)(dat)
    #    v1    v2   v3    v4
    #1 TRUE FALSE TRUE FALSE