[R] data.frame, data types, and apply

Uwe Ligges ligges at statistik.uni-dortmund.de
Wed Mar 2 19:13:44 CET 2005


Vincent Detours wrote:

> Dear all,
> 
> Here is an issue I often stumble on.
> 
> 1- colunm types in data.frames.
> 
> -------------------------------
> 
>>d <- data.frame(x=as.character(c("a", "b", "c")), y=as.numeric(c(1, 2, 3)))
>>d
> 
>   x y
> 1 a 1
> 2 b 2
> 3 c 3
> 
>>is.numeric(d[1,2])
> 
> [1] TRUE
> 
>>is.numeric(d[1,1])
> 
> [1] FALSE
> 
>>apply(d, c(1,2), is.numeric)
> 
>       x     y
> 1 FALSE FALSE
> 2 FALSE FALSE
> 3 FALSE FALSE
> 
> -------------------------------
> 
> All item in column "y" should be TRUE right? What should I do to apply
> a function only to numerics in d? (beside using nested 'for' loops)

It is correct!
d is a data.frame, but apply() works on matrices. So d is coerced to a 
matrix which means that there need to be only one mode - and that is 
character!

Check the columns as in

   sapply(d, is.numeric)


Uwe Ligges



> Thanks for your help, and for all the great software.
> 
> 
> Vincent Detours
> 
> ______________________________________________
> R-help at stat.math.ethz.ch mailing list
> https://stat.ethz.ch/mailman/listinfo/r-help
> PLEASE do read the posting guide! http://www.R-project.org/posting-guide.html




More information about the R-help mailing list