[R] return NA instead zero when summing over an empty range?

Duncan Murdoch murdoch.duncan at gmail.com
Wed Oct 27 12:41:20 CEST 2010


On 27/10/2010 6:08 AM, Martin Ivanov wrote:
>   Dear R users,
>
> the colSums function from the base package returns zero if there are no values in a range to be summed over (after removing missing values with na.rm = TRUE). Is there some way to make it return NA in that case just like colMeans does? Or any other function or some good way to achieve that? Any ideas are be welcome.

That doesn't make sense in most situations, but an easy way to do it 
would be to multiply colMeans by the count of valid entries.  For example,

M <- matrix(NA, 2, 2)
colSums(M, na.rm=TRUE)  # shows zeros

colMeans(M, na.rm=TRUE)*colSums(!is.na(M))  # shows NAs

Warning:  I found a bug in this version.  If there are zero rows in M, 
the dimension of the matrix gets lost in !is.na(M) and colSums will 
throw an error.

Duncan Murdoch



More information about the R-help mailing list