[R] is this a bug (apply and class) ?

Chuck Cleland ccleland at optonline.net
Fri Aug 1 10:59:35 CEST 2008


On 8/1/2008 4:49 AM, David Hajage wrote:
> Hello R users,
> 
> I run this code under windows XP and R 2.7.1 :
> 
>> head(esoph)
>   agegp     alcgp    tobgp ncases ncontrols
> 1 25-34 0-39g/day 0-9g/day      0        40
> 2 25-34 0-39g/day    10-19      0        10
> 3 25-34 0-39g/day    20-29      0         6
> 4 25-34 0-39g/day      30+      0         5
> 5 25-34     40-79 0-9g/day      0        27
> 6 25-34     40-79    10-19      0         7
>> class(esoph$agegp)
> [1] "ordered" "factor"
>> class(esoph$alcgp)
> [1] "ordered" "factor"
>> class(esoph$tobgp)
> [1] "ordered" "factor"
>> class(esoph$ncases)
> [1] "numeric"
>> class(esoph$ncontrols)
> [1] "numeric"
>> apply(esoph, 2, class)
>       agegp       alcgp       tobgp      ncases   ncontrols
> "character" "character" "character" "character" "character"
> 
> I don't understand why the result is all "character"...

   Because the data frame is coerced to a matrix by apply():

"If X is not an array but has a dimension attribute, apply attempts to 
coerce it to an array via as.matrix if it is two-dimensional (e.g., data 
frames)..."

   Try lapply() or sapply() instead.

 > lapply(esoph, class)
$agegp
[1] "ordered" "factor"

$alcgp
[1] "ordered" "factor"

$tobgp
[1] "ordered" "factor"

$ncases
[1] "numeric"

$ncontrols
[1] "numeric"

> Thanks a lot.
> 
> 	[[alternative HTML version deleted]]
> 
> ______________________________________________
> R-help at r-project.org mailing list
> https://stat.ethz.ch/mailman/listinfo/r-help
> PLEASE do read the posting guide http://www.R-project.org/posting-guide.html
> and provide commented, minimal, self-contained, reproducible code. 

-- 
Chuck Cleland, Ph.D.
NDRI, Inc. (www.ndri.org)
71 West 23rd Street, 8th floor
New York, NY 10010
tel: (212) 845-4495 (Tu, Th)
tel: (732) 512-0171 (M, W, F)
fax: (917) 438-0894



More information about the R-help mailing list