[R] How to apply functions over rows of multiple matrices

Johannes Hüsing johannes at huesing.name
Thu Aug 9 18:27:49 CEST 2007


Dear ExpRts,
I would like to perform a function with two arguments
over the rows of two matrices. There are a couple of
*applys (including mApply in Hmisc) but I haven't found
out how to do it straightforward.

Applying to row indices works, but looks like a poor hack
to me:

sens <- function(test, gold) {
  if (any(gold==1)) {
    sum(test[which(gold==1)]/sum(which(gold==1)))
  } else NA
}

numtest <- 6
numsubj <- 20

newtest <- array(rbinom(numtest*numsubj, 1, .5),
    dim=c(numsubj, numtest))
goldstandard <- array(rbinom(numtest*numsubj, 1, .5),
    dim=c(numsubj, numtest))

t(sapply(1:nrow(newtest), function(i) {
    sens(newtest[i,], goldstandard[i,])}))

Is there any shortcut to sapply over the indices?

Best wishes


Johannes



More information about the R-help mailing list