[R] Using a mathematical expression in sapply() XXXX

Meyners, Michael meyners.m at pg.com
Wed Jan 4 15:02:53 CET 2012


Dan,

It depends on what you want to achieve. I suspect you just want to remove missing values before summing; if so, consider

sapply(x, sum, na.rm=TRUE)

instead. To make your code running, try

sapply(x, function(x) sum(!is.na(x)))

However, this would just count the number of non-missing values per subgroup, not the sum of the values. 

Similarly, 

sapply(x, function(x) sum(x, na.rm=TRUE))

would follow the same rationale but give the sums (with missing values removed), i.e. the same results as the first line of code. I'd rather choose the first option than this one, though.

Of course, you could also define a new function 

sum1 <- function(x) sum(!is.na(x)) # or probably rather sum(x, na.rm=TRUE), depending on your needs

and then use 

sapply(x, sum1)

but that seems a bit overkill, I'd say...

HTH, Michael


> -----Original Message-----
> From: r-help-bounces at r-project.org [mailto:r-help-bounces at r-
> project.org] On Behalf Of Dan Abner
> Sent: Wednesday, January 04, 2012 14:41
> To: r-help at r-project.org
> Subject: [R] Using a mathematical expression in sapply() XXXX
> 
> Hello everyone,
> 
> I have the following call to sapply() and error message. Is the most
> efficient way to deal with this to make sum(!is.na(x)) a function in a
> separate line prior to this call? If not, please advise.
> 
> N.Valid=sapply(x,sum(!is.na(x)))
> Error in match.fun(FUN) :
>   'sum(!is.na(x))' is not a function, character or symbol
> 
> 
> Thanks!
> 
> Dan
> 
> 	[[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.



More information about the R-help mailing list