Home > Blockchain >  How to find the position of the maximum value in a list in R?
How to find the position of the maximum value in a list in R?

Time:11-05

This seems like it should be very simple, but I can't figure it out or find a solution online.

I have a list

test<-list(a = list(c(4543, 25234, 56346, 676), c(545, 34647, 567567, 
4564), c(785, 343, 95, 435)), b = list(c(90823, 2341, 989, 5645
), c(210938, 342345, 345, 78678), c(2094234, 2343, 23466, 45654
)))

How do I find the position of the maximum value in the list?

the answer is test[["b"]][[3]][1] or test[[2]][[3]][1]

CodePudding user response:

It's little mess, but it will give you location of maximum value

library(stringr)
library(dplyr)

x <- which.max(unlist(test))
y <- str_split(names(x), "", simplify = T)
a <- y[1]


z <- sapply(test[[a]], length) %>% cumsum
b <- which(z > as.numeric(y[2]))
c <- as.numeric(y[2]) - z[b-1]

test[[a]][[b]][[c]]

[1] 2094234

In this code, a, b, and c indicate location. If you need more generalized version, please let me know

CodePudding user response:

You can try the code below

df <- do.call(
  rbind,
  Map(
    function(x, y) {
      transform(
        stack(setNames(x, seq_along(x))),
        lb = ave(seq_along(ind), ind, FUN = seq_along),
        lt = y
      )
    },
    test,
    names(test)
  )
)

df[order(-df$values), c("values", "lt", "ind", "lb")]

which gives

      values lt ind lb
b.9  2094234  b   3  1
a.7   567567  a   2  3
b.6   342345  b   2  2
b.5   210938  b   2  1
b.1    90823  b   1  1
b.8    78678  b   2  4
a.3    56346  a   1  3
b.12   45654  b   3  4
a.6    34647  a   2  2
a.2    25234  a   1  2
b.11   23466  b   3  3
b.4     5645  b   1  4
a.8     4564  a   2  4
a.1     4543  a   1  1
b.10    2343  b   3  2
b.2     2341  b   1  2
b.3      989  b   1  3
a.9      785  a   3  1
a.4      676  a   1  4
a.5      545  a   2  1
a.12     435  a   3  4
b.7      345  b   2  3
a.10     343  a   3  2
a.11      95  a   3  3

and you will the order of values with associated indices in the nested list.

  • Related