[R] apply function

Berwin A Turlach berwin at maths.uwa.edu.au
Thu May 15 09:16:36 CEST 2008


G'day Shuba,

On Thu, 15 May 2008 12:18:58 +0530
"Shubha Vishwanath Karanth" <shubhak at ambaresearch.com> wrote:

> Getting a strange result using ?apply. Please look into the below
> codes:
>
> d=data.frame(a=c(1,2,3),b=c("A","B","C"),c=c(TRUE,FALSE,FALSE),d=c(T,F,F))
> 
> > class(d[,1])
> 
> [1] "numeric"
> 
> > class(d[,2])
> 
> [1] "factor"
> 
> > class(d[,3])
> 
> [1] "logical"
> 
> > class(d[,4])
> 
> [1] "logical"
> 
> > apply(d,2,class)
> 
>           a           b           c           d 
> 
> "character" "character" "character" "character" 
[....]
> Why is this so? 

?apply
The first argument to apply is an *array*, not a data.frame.  In an
array, all elements have to be of the same type, so when your
data.frame is coerced into an array the target type of the coercion
depends on which components you select.

> How do I get the actual classes of columns of my dataframe d?

Something like:

R> lapply(d, class)
$a
[1] "numeric"

$b
[1] "factor"

$c
[1] "logical"

$d
[1] "logical"

could be used.

HTH.

Best wishes,

	Berwin

=========================== Full address =============================
Berwin A Turlach                            Tel.: +65 6515 4416 (secr)
Dept of Statistics and Applied Probability        +65 6515 6650 (self)
Faculty of Science                          FAX : +65 6872 3919       
National University of Singapore     
6 Science Drive 2, Blk S16, Level 7          e-mail: statba at nus.edu.sg
Singapore 117546                    http://www.stat.nus.edu.sg/~statba



More information about the R-help mailing list