开发者

Sum up minima of data pairs in a matrix

I would lik开发者_StackOverflowe to compare the elements of two rows in a matrix and then sum up the minima of the data pairs.

For example in a matrix like this the result should be 3 (1+1+1+0)

> m
  col1 col2 col3 col4
a    2    1    4    4
b    1    2    1    0

I tried it like this:

> findmin <- function (x) for (i in 1:ncol(x)) {min(x[1,i], x[2,i])}
> res <- sum(findmin(m))
> res
[1] 0

I think the problem is that the loop returns NULL as a value. How can i avoid this? Or is there a more elegant way to do it avoiding the for loop?


apply() is your friend:

R> M <- matrix(c(2,1,4,4,1,2,1,0), 2, 4, byrow=TRUE)
R> M
     [,1] [,2] [,3] [,4]
[1,]    2    1    4    4
[2,]    1    2    1    0
R> apply(M, 1, min)                       # goes row-wise
[1] 1 0
R> apply(M, 2, min)                       # goes column-wise
[1] 1 1 1 0
R> sum(apply(M, 2, min))
[1] 3
R> 


sum(apply(m, 2, min)) does the trick:

> m <- matrix(c(2,1,4,4,1,2,1,0), 2, byrow=TRUE)

> m
     [,1] [,2] [,3] [,4]
[1,]    2    1    4    4
[2,]    1    2    1    0

> sum(apply(m, 2, min))
[1] 3


A more "R" way to solve this task would be with an apply function: sum(apply(m, 2, min))

Your for loop didn't work because you weren't storing or returning any value. Here's how to fix your for loop. Note that preallocating the size of out makes it execute much faster:

findmin <- function(x){
    out <- rep(NA, ncol(x))
    for (i in 1:ncol(x)) {
        out[i] <- min(x[1,i], x[2,i])
    }
    return(out)
}
> findmin(m)
[1] 1 1 1 0
0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜