[R] sum() returns 0 not NA
(Ted Harding)
Ted.Harding at manchester.ac.uk
Thu Apr 15 15:07:14 CEST 2010
On 15-Apr-10 12:37:42, Wilmar Igl 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
For the same reason that:
sum(logical(0))
# [1] 0
If x is a numeric vector, possibly with NAs,
sum(x,na.rm=TRUE)
will first remove any NAs from x, and then execute sum() on
what is left.
In the case of your example, after removing the NAs from c(NA,NA)
there is nothing left. The fact that it comes out 'logical' is
another issue:
x <- c(NA,NA)
x[!is.na(x)]
# logical(0)
c(NA,NA)[-(1:2)]
# logical(0)
while:
c(3,4)[-(1:2)]
numeric(0)
The point is that the type of c(NA,NA) is "logical"
str(c(NA,NA))
# logi [1:2] NA NA
Ted.
--------------------------------------------------------------------
E-Mail: (Ted Harding) <Ted.Harding at manchester.ac.uk>
Fax-to-email: +44 (0)870 094 0861
Date: 15-Apr-10 Time: 14:07:10
------------------------------ XFMail ------------------------------
More information about the R-help
mailing list