[R] Sum of a couple of variables of which a few have NA values

David Winsemius dwinsemius at comcast.net
Tue Jan 10 17:48:12 CET 2012


On Jan 10, 2012, at 11:25 AM, Petra Opic wrote:

> Dear everyone,
>
> I have looked all over the internet but I cannot find a way to solve  
> my problem.

? rowSums   # has an na.rm argument

>
> In my data I want to sum a couple of variables. Some of these
> variables have NA values, and when I add them together, the result is
> NA
snip
> attach(dat)

You would be well-advised to forget `attach`. Use with(dat, ...)  
instead. It will prevent frustration and embarrassing postings to rhelp.

>
> dat$sum <- var2 + var3 + var4

The plus infix operator does not have an na.rm argment

dat$sum <- rowSums(dat[ , 2:4] , na.rm=TRUE)

-- 

David Winsemius, MD
West Hartford, CT



More information about the R-help mailing list