[R] strange behaviour of is.factor()

Uwe Ligges ligges at statistik.tu-dortmund.de
Wed Jan 16 11:48:41 CET 2008



vito muggeo wrote:
> Dear all,
> It appears that the function is.factor() returns different results when 
> used inside the apply() function: that is, is.factor() fails to 
> recognize a factor..
> Where is the trick?
> 
> many thanks,
> vito
> 
>  > df1<-data.frame(y=1:10,x=rnorm(10),g=factor(c(rep("A",6),rep("B",4))))
>  > is.factor(df1[,1])
> [1] FALSE
>  > is.factor(df1[,2])
> [1] FALSE
>  > is.factor(df1[,3])
> [1] TRUE
>  > is.factor(df1$g)
> [1] TRUE
>  > apply(df1,2,is.factor)
>      y     x     g
> FALSE FALSE FALSE



Well, apply works on matrices and arrays, hence df1 is coerced to a 
matrix, i.e. you invoked in fact the same as
    apply(as.matrix(df1), 2, is.factor)
hence you get a matrix of character values which can be confirmed by
   apply(df1, 2, is.character)

Anyway, what you really want is:
    sapply(df1, is.factor)

Uwe Ligges




>  >
>  > R.version
>                 _
> platform       i386-pc-mingw32
> arch           i386
> os             mingw32
> system         i386, mingw32
> status
> major          2
> minor          6.1
> year           2007
> month          11
> day            26
> svn rev        43537
> language       R
> version.string R version 2.6.1 (2007-11-26)
>  >
>




More information about the R-help mailing list