Skip to content
Prev 201653 / 398506 Next

How to sum only a few elements in a line

One of the nice things about the S language is
that arguments functions are not altered by the
function.  When the function appears to alter
an argument it is really altering a copy of it.
Thus you can write a function like
    f <- function(matrix) {
        matrix[matrix==9] <- 0
        rowSums(matrix)
    }
and use it as
    > myMatrix <- rbind(c(0,1,0,1,1,9,1), c(9,9,9,9,9,17,9))
    > f(myMatrix)
    [1]  4 17
    > myMatrix # not altered by running f over it
         [,1] [,2] [,3] [,4] [,5] [,6] [,7]
    [1,]    0    1    0    1    1    9    1
    [2,]    9    9    9    9    9   17    9

By the way, it would help if you wrote your example data
as an S expression, e.g., rbind(c(...),c(...)), and not
as an expression in some other language, "[ 1 1 9 ]".

Bill Dunlap
Spotfire, TIBCO Software
wdunlap tibco.com
-tp26519740p26519740.html