My first instinct was to suggest using sum() , since you can use the na.rm argument. However, this does not work, since sum() reduces its arguments to a single scalar value, and not to a vector.
This means that you need to write a parallel sum function. Let us call it psum() , similar to the base function R pmin() or pmax() :
psum <- function(..., na.rm=FALSE) { x <- list(...) rowSums(matrix(unlist(x), ncol=length(x)), na.rm=na.rm) }
Now configure some data and use psum() to get the desired vector:
dat <- data.frame( x = c(1,2,3, NA), y = c(NA, 4, 5, NA)) transform(dat, new=psum(x, y, na.rm=TRUE)) xy new 1 1 NA 1 2 2 4 6 3 3 5 8 4 NA NA 0
Similarly, you can define parallel product or pprod() as follows:
pprod <- function(..., na.rm=FALSE) { x <- list(...) m <- matrix(unlist(x), ncol=length(x)) apply(m, 1, prod, na.rm=TRUE) } transform(dat, new=pprod(x, y, na.rm=TRUE)) xy new 1 1 NA 1 2 2 4 8 3 3 5 15 4 NA NA 1
This pprod example provides a generic template for what you want to do: Create a function that uses apply() to sum the input matrix into the desired vector.