[R] apply and sapply oddity

Duncan Murdoch murdoch.duncan at gmail.com
Wed Oct 24 01:06:40 CEST 2012


On 12-10-23 6:56 PM, Brian wrote:
> Hi List,
>
> why are the results of the two bits of below code different?
>
>   > sapply(1:ncol(d.f), function(i) mode(d.f[,i]))
>    [1] "character" "character" "numeric"   "numeric"   "numeric" "numeric"
>    [7] "numeric"   "numeric"   "numeric"   "numeric"   "numeric" "numeric"
> [13] "numeric"   "numeric"   "character"
>   > apply(d.f, 2, mode)
>            stn         time     gre000z0     prestas0     tre200s0 ure200s0
>    "character"  "character"  "character"  "character"  "character"
> "character"
>       usp200s0     fve010z0     dkl010z0        chron      CO_sync
> CO2_dry_sync
>    "character"  "character"  "character"  "character"  "character"
> "character"
> CH4_dry_sync     H2O_sync       wd.bin
>    "character"  "character"  "character"
>
> I am a bit vexed. I thought those two would be equivalent.

As the man page says, apply coerces a dataframe to a matrix before doing 
the calculations.  In a matrix, all the columns are the same type.

Duncan Murdoch




More information about the R-help mailing list