[R] Handling NA values

Marc Schwartz marc_schwartz at me.com
Sat Feb 16 19:07:51 CET 2013


On Feb 16, 2013, at 11:55 AM, Christofer Bogaso <bogaso.christofer at gmail.com> wrote:

> Hello again,
> 
> I have a question on who sum() handle the NA values.
> 
>> sum(c(NA, 1), na.rm = TRUE)
> [1] 1
> 
> 
> I understand this. However could not agree with following:
> 
>> sum(c(NA, NA), na.rm = TRUE)
> [1] 0
> 
> 
> Where this '0' is coming from? Should not it be NA itself?
> 
> Thanks and regards,



The result of:

  sum(c(NA, NA), na.rm = TRUE)

is to sum an empty set, hence the 0.


> na.omit(c(NA, NA))
logical(0)
attr(,"na.action")
[1] 1 2
attr(,"class")
[1] "omit"


> sum(logical(0))
[1] 0


If you retained the NA's, then the result is undefined:

> sum(c(NA, NA))
[1] NA


See:

  http://rwiki.sciviews.org/doku.php?id=tips:surprises:emptysetfuncs

for more information.

Regards,

Marc Schwartz



More information about the R-help mailing list