[R] sum() returns 0 not NA

Joshua Wiley jwiley.psych at gmail.com
Tue Apr 20 19:07:31 CEST 2010


As a disclaimer, I cannot say that this is why sum() was designed as it was.

0 is the sum of a set with no elements, the empty set {}.  When
na.rm=TRUE, NA values are removed.  When the only values are NA (as in
your example c(NA, NA) ), and you remove them all, you are taking the
sum of no elements, which is 0.

Also note the behavior of

sum() # returns 0

sum is one of the few functions that you can simply call that will not
return an error.

HTH,

Josh

On Tue, Apr 20, 2010 at 9:42 AM,  <will.eagle at gmx.net> wrote:
> Dear all,
>
> just a stupid R question, since the results puzzle me a bit:
>
>> sum(c(NA,NA), na.rm=TRUE)
> [1] 0
>>  NA + NA
> [1] NA
>> NA + 1
> [1] NA
>>
>
> Why does sum(c(NA,NA), na.rm=TRUE) return 0 and not NA?
>
> Thanks in advance,
>
> Will
>
> ______________________________________________
> 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.
>



-- 
Joshua Wiley
Senior in Psychology
University of California, Riverside
http://www.joshuawiley.com/



More information about the R-help mailing list