Martin Ivanov
2010-Oct-27 10:08 UTC
[R] return NA instead zero when summing over an empty range?
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. Regards, Martin Ivanov ----------------------------------------------------------------- ????? ?????????? ?????? ??? Vesti.bg! http://www.vesti.bg/
Duncan Murdoch
2010-Oct-27 10:41 UTC
[R] return NA instead zero when summing over an empty range?
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