qed
qed

Reputation: 23154

Compare corresponding elements of a list in R

Here is the code for generating the list:

    x = matrix(1, 4, 4)
    x[2,2] = 5
    x[2:3, 1] = 3
    x
    #     [,1] [,2] [,3] [,4]
    #[1,]    1    1    1    1
    #[2,]    3    5    1    1
    #[3,]    3    1    1    1
    #[4,]    1    1    1    1
    res = apply(x, 2, function(i) list(m=max(i), idx=which(i == max(i))))
    res
    #[[1]]
    #[[1]]$m
    #[1] 3
    #
    #[[1]]$idx
    #[1] 2 3
    #
    #
    #[[2]]
    #[[2]]$m
    #[1] 5
    #
    #[[2]]$idx
    #[1] 2
    #
    #
    #[[3]]
    #[[3]]$m
    #[1] 1
    #
    #[[3]]$idx
    #[1] 1 2 3 4
    #
    #
    #[[4]]
    #[[4]]$m
    #[1] 1
    #
    #[[4]]$idx
    #[1] 1 2 3 4

Now i want to compare the $m in each sub-list, get the maximum and its index in the matrix, i can do this way

    mvector = vector('numeric', 4)
    for (i in 1:4) {
     mvector[i] = res[[i]]$m
     }
    mvector
    #[1] 3 5 1 1
    max_m = max(mvector)
    max_m
    #[1] 5
    max_col = which(mvector == max_m)
    max_row = res[[max_col]]$idx
    max_row
    #[1] 2
    x[max_row, max_col]
    #[1] 5

I am wondering if there is a simpler way of doing this?

Upvotes: 2

Views: 311

Answers (1)

flodel
flodel

Reputation: 89107

Do you have to build that list? You can work on the matrix x directly:

max value (your max_m):

max(x)
# [1] 5

where in the matrix this value is found (first match only):

which.max(x)
# [1] 5

or its row and column indices (your max.row and max.col):

arrayInd(which.max(x), dim(x))
#      [,1] [,2]
# [1,]    2    2

And in case of multiple maximums, you can get all of them by replacing which.max(x) with which(x == max(x)) in the two statements above.

Upvotes: 3

Related Questions