Marcio Resende wrote:
Hello,

I have a matrix with the numbers 0,1 and 9
I would like to write a function that could sum each line skiping everytime
a number 9 appears
for example
[0 1 0 1 1 9 1]
the sum would be 4.
However I cannot replace 9 by 0 otherwise after the sum is done I wouldn´t
be able to distiguish which ones were real zeros and which ones were nines
replaced by zero just to sum.
Thank you very much

In order to distinguish 'real' 0s from those resulting
from elimination of 9s (without going back to the original
matrix), you can do this:

f <- function(x){
  Sum <- sum(x[x != 9])
  has_9 <- 9 %in% x
  c(Sum = Sum, has_9 = has_9)
}

# make a sample matrix
M <- matrix(sample(c(0,1,9), 30, TRUE), 6, 5)

# get sums and whether the row contained one or more 9s
t(apply(M, 1, f))

 -Peter Ehlers

______________________________________________
R-help@r-project.org mailing list
https://stat.ethz.ch/mailman/listinfo/r-help
PLEASE do read the posting guide http://www.R-project.org/posting-guide.html
and provide commented, minimal, self-contained, reproducible code.

Reply via email to