Johannes Hüsing
2007-Aug-09 16:27 UTC
[R] How to apply functions over rows of multiple matrices
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
Gabor Grothendieck
2007-Aug-09 17:03 UTC
[R] How to apply functions over rows of multiple matrices
Is sens really what you want? The denominator is the indexes, e.g. if a row in goldstandard were c(0, 0, 1, 1) then you would be dividing by 3+4. Also test[which(gold == 1)] is the same as test[gold == 1] which is the same test * gold since gold has only 0 and 1's in it. Perhaps what you really intend is to take the average over those elements in each row of the first matrix which correspond to 1's in the second in the corresponding row of the second. In that case its just: rowSums(newtest * goldstandard) / rowSums(goldstandard) On 8/9/07, Johannes H?sing <johannes at huesing.name> wrote:> 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 > > ______________________________________________ > R-help at stat.math.ethz.ch 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. >