[R] How to force aggregate to exclude NA ?

Daren Tan daren76 at hotmail.com
Sun Dec 7 17:10:47 CET 2008


How to use the na.rm function outside aggregate ? I tried 
 
na.rm <- function(f) {
  function(x, ...) f(x[!is.na(x)], ...)
}
 
 
>na.rm(sum(c(NA,1,2)))

function(x, ...) f(x[!is.na(x)], ...)


> na.rm(sum, c(NA,1,2))
Error in na.rm(sum, c(NA, 1, 2)) : unused argument(s) (c(NA, 1, 2))

 


> Date: Sun, 7 Dec 2008 07:45:14 -0600
> From: h.wickham at gmail.com
> To: daren76 at hotmail.com
> Subject: Re: [R] How to force aggregate to exclude NA ?
> CC: r-help at stat.math.ethz.ch
> 
>>> aggregate(m[,-c(1:2)], by=list(m[,1]), mysum) <----------------- this computes correctly.
>> Group.1 C D
>> 1 A 3 2
>> 2 B 15 13
>> 3 C 10 10
>> 4 D 6 7
>> 5 E 9 8
>>
>>> aggregate(m[,-c(1:2)], by=list(m[,1]), mylength) <----------------- this computes correctly.
>> Group.1 C D
>> 1 A 1 1
>> 2 B 5 4
>> 3 C 3 4
>> 4 D 2 3
>> 5 E 4 4
>>
>> There are other statistics I need to compute e.g. var, sd, and it is a hassle to create customized versions to exclude NA. Any alternative approaches ?
> 
> How about writing a function to do the customisation for you?
> 
> na.rm <- function(f) {
> function(x, ...) f(x[!is.na(x)], ...)
> }
> 
> aggregate(m[,-c(1:2)], by=list(m[,1]), na.rm(sum))
> aggregate(m[,-c(1:2)], by=list(m[,1]), na.rm(length))
> 
> Hadley
> 
> -- 
> http://had.co.nz/



More information about the R-help mailing list