[R] sapply() and by()

David Winsemius dwinsemius at comcast.net
Mon Aug 6 20:00:26 CEST 2012


On Aug 6, 2012, at 7:34 AM, Dominic Roye wrote:

> Hello everyone,
>
>
> I have a dataset with 5 colums (4 colums with thresholds of weather
> stations and one with month - data of 5 years). Now I would like to
> calculate the average for each month.
>
> I tried this unsuccessfully:
>
> lf.med <- sapply(LF[,1:4],mean,)

If you want to group calculations within categories then sapply is not  
the right function to turn to immediately. Use one of 'aggregate',  
'tapply' or 'ave'.

> Error in mean.default(X[[1L]], ...) :
>  'trim' must be numeric and have length 1

It is telling you that the unnamed third argument was matched to the  
'trim' parameter of the function 'mean'.


Perhaps:

aggregate( LF[,1:4], list(LF[,5]), mean)


>
> With
>
> lf.med <- by(LF[,1:4],LF[,5],mean)
>
> It works, but its deprecated.

Actually what is deprecated is the function `mean.data.frame`.

>
>
> Any help is greatly appreciated!!!  Thanky everybody`!!


Minimal example. PLEASE.
>
> Dominic
>
>> dput(LC)

Please do note that you offered an object 'LC' but you code referred  
to 'LF'.

> structure(list(Serra.da.Foladoira = c(21.1359565217391,  
> 21.7184782608695,
> 23.5492608695652, 23.4660434782608, 23.6740869565217,  
> 21.1775652173913,
> 19.8460869565217, 23.3412173913043, 22.8835217391304,  
> 24.3398260869565,

snipped 1800+ length vector

>>
>
> 	[[alternative HTML version deleted]]
>
>
 >>>>>>>>>
> and provide commented, minimal, self-contained, reproducible code.
                         ^^^^^^^^

-- 
David Winsemius, MD
Alameda, CA, USA



More information about the R-help mailing list