Question

I want to use lapply to get indexes of minimum values of a list.

I have a list min:

> min
  $A
  [1] 15.4 15.9 16.4 14.5 17.1 .... and so on

  $B
  [1] 18.3 14.9 15.3

Using lapply I can sort this list:

> min2<-lapply(min, sort)
 $A  [1] 14.4 14.5 14.5 14.5 14.6 ... and so on
 $B [1] 14.9 15.3 18.3

How can I now get indexes of min based on results of min2?

Was it helpful?

Solution

mapply and match

x <- list(a = rnorm(5),
          b = rnorm(5))
# $a
# [1] -0.05417899 -0.28140108 -0.51207379  0.73572854  1.24535765
# 
# $b
# [1]  1.1580326  0.7900556  0.9595224 -1.2232270  0.6621114

y <- lapply(x, sort)

# $a
# [1] -0.51207379 -0.28140108 -0.05417899  0.73572854  1.24535765
# 
# $b
# [1] -1.2232270  0.6621114  0.7900556  0.9595224  1.1580326

mapply(match, y, x)
#      a b
# [1,] 3 4
# [2,] 2 5
# [3,] 1 2
# [4,] 4 3
# [5,] 5 1

edit:

z <- as.matrix(mapply(match, y, x))
#      a b
# [1,] 3 4
# [2,] 2 5
# [3,] 1 2
# [4,] 4 3
# [5,] 5 1

zz <- LETTERS[1:5]

matrix(zz[z], ncol = 2)

     [,1] [,2]
[1,] "C"  "D" 
[2,] "B"  "E" 
[3,] "A"  "B" 
[4,] "D"  "C" 
[5,] "E"  "A" 
Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top