R check if a variable is a factor

19,788

Solution 1

Try using sapply or lapply instead of you for-loop as follows:

variable <- data.frame(test1,test2)
sapply(variable,is.factor) # returns a vector
test1 test2 
 TRUE FALSE

lapply(variable,is.factor) # returns a list
$test1
[1] TRUE

$test2
[1] FALSE

Or you can easily use your function instead of is.factor

Edit: (thanks to Ananda Mahto) vapply is even faster than sapply

require(microbenchmark)
microbenchmark(
  vapply(variable,is.factor, c(is.factor=FALSE)),
  sapply(variable,is.factor),
  lapply(variable,is.factor),
  times = 10000
)
Unit: microseconds
                                              expr    min     lq median     uq      max neval
 vapply(variable, is.factor, c(is.factor = FALSE)) 12.248 13.829 14.618 15.409  959.698 10000
                       sapply(variable, is.factor) 31.608 35.560 36.350 37.534 1159.618 10000
                       lapply(variable, is.factor)  9.877 11.458 11.853 12.644  935.597 10000

Solution 2

This is an evaluation problem. The character arrays "test1" or "test2" are not factors.

> is.factor(get(variable[1]))
[1] TRUE
> is.factor(get(variable[2]))
[1] FALSE
Share:
19,788
Head and toes
Author by

Head and toes

Updated on June 23, 2022

Comments

  • Head and toes
    Head and toes almost 2 years

    I am trying to write a loop which can apply to a dataframe. The loop will basically check each variable in the dataframe and tell me which variable is a factor.

    An example:

    test1<-c("red","red","blue","yellow")
    test1<-as.factor(test1)
    test2<-c(1,2,3,4)
    
    variable<-c("test1","test2")
    count<-2
    
    for (i in 1:count)
    {
            if (is.factor(paste(variable[i]))==TRUE) 
            { 
               print("This is a factor")
            }
    }
    

    test1 variable is supposed to be a factor and therefore the sentence "This is a factor" should be printed. However nothing happened. I wonder why?

  • A5C1D2H2I1M1N2O1R2T1
    A5C1D2H2I1M1N2O1R2T1 over 9 years
    Why are you neglecting vapply :-)
  • Rentrop
    Rentrop over 9 years
    Thanks! Never used vapply before. But i am going to in the future