Compare corresponding elements of a list in R -


here code generating 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 want compare $m in each sub-list, maximum , index in matrix, can way

    mvector = vector('numeric', 4)     (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 wondering if there simpler way of doing this?

do have build list? can work on matrix x directly:

max value (your max_m):

max(x) # [1] 5 

where in matrix value found (first match only):

which.max(x) # [1] 5 

or row , column indices (your max.row , max.col):

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

and in case of multiple maximums, can of them replacing which.max(x) which(x == max(x)) in 2 statements above.


Comments

Popular posts from this blog

linux - Does gcc have any options to add version info in ELF binary file? -

android - send complex objects as post php java -

charts - What graph/dashboard product is facebook using in Dashboard: PUE & WUE -