[R] Sum function and missing values --- need to mimic SAS sum function
istazahn at gmail.com
Mon Jan 26 22:17:37 CET 2015
Try with na.rm=TRUE.
On Jan 26, 2015 4:04 PM, "MacQueen, Don" <macqueen1 at llnl.gov> wrote:
> I'm a little puzzled by the assertion that the result is 0.0 when all the
> elements are NA:
> > sum(NA)
>  NA
> > sum(c(NA,NA))
>  NA
> > sum(rep(NA, 10))
>  NA
> > sum(as.numeric(letters[1:4]))
>  NA
> Warning message:
> NAs introduced by coercion
> Considering that the example snippet of code has several other aspects
> besides using sum(), among them subsetting rows of a data frame when there
> are apparently NAs in some its variables ... I wonder if the reason for
> the failure of that snippet has been misunderstood?
> Don MacQueen
> Lawrence Livermore National Laboratory
> 7000 East Ave., L-627
> Livermore, CA 94550
> On 1/25/15, 3:21 PM, "Allen Bingham" <aebingham2 at gmail.com> wrote:
> >I understand that in order to get the sum function to ignore missing
> >I need to supply the argument na.rm=TRUE. However, when summing numeric
> >values in which ALL components are "NA" ... the result is 0.0 ... instead
> >(what I would get from SAS) of NA (or in the case of SAS ".").
> >Accordingly, I've had to go to 'extreme' measures to get the sum function
> >result in NA if all arguments are missing (otherwise give me a sum of all
> >non-NA elements).
> >So for example here's a snippet of code that ALMOST does what I want:
> >In reality this does NOT give me records with NA for SumValue ... but it
> >doesn't give me values for any records in which both Variable.1 and
> >Variable.2 are NA --- which is "good enough" for my purposes.
> >I'm guessing with a little more work I could come up with a way to adapt
> >code above so that I could get it to work like SAS's sum function ...
> >... but before I go that extra mile I thought I'd ask others if they know
> >functions in either base R ... or in a package that will better mimic the
> >SAS sum function.
> >Any suggestions?
> >Allen Bingham
> >aebingham2 at gmail.com
> >R-help at r-project.org mailing list -- To UNSUBSCRIBE and more, see
> >PLEASE do read the posting guide
> >and provide commented, minimal, self-contained, reproducible code.
> R-help at r-project.org mailing list -- To UNSUBSCRIBE and more, see
> PLEASE do read the posting guide
> and provide commented, minimal, self-contained, reproducible code.
[[alternative HTML version deleted]]
More information about the R-help