user9798936
user9798936

Reputation:

How to extract the mimimum values from the list of list and give them a name in r

I have a list of a list with high complicated data. I would like to compare the values of each list and extract the smallest values. For simplicity, I provide a similar example.

s <- c(1,2,3)
ss <- c(4,5,6)
S <- list(s,ss)
h <- c(4,8,7)
hh <- c(0,3,4)
H <- list(h,hh)
HH <- list(S,H)

I would like to compare the element of each list with the element of the corresponding list and extract the smallest values. For example, the following are the values of HH list.

   > HH
[[1]]
[[1]][[1]]
[1] 1 2 3

[[1]][[2]]
[1] 4 5 6


[[2]]
[[2]][[1]]
[1] 4 8 7

[[2]][[2]]
[1] 0 3 4

Now, I would like to compare

[[1]]
[[1]][[1]]
[1] 1 2 3

with

[[2]]
[[2]][[1]]
[1] 4 8 7

For example, 1 < 4, so I will select 1. For the second element, 2 < 8, so I will select 2. So, I would like to compare the elements of [[1]][[1]] with the elements of [[2]][[1]], and [[1]][[2]] with [[2]][[2]].

Then, I would like to print the name of the list. For example,

I expected to have similar to the following:

1 < 4, the first element of the first model is selected.

Upvotes: 1

Views: 52

Answers (2)

akrun
akrun

Reputation: 887048

We could use a general solution (i.e. if there are many list elements) transpose from purrr to rearrange the list elements, and then use max.col to get the index

library(magrittr)
library(purrr)
HH %>%
  transpose %>%
  map(~ .x %>%
        invoke(cbind, .) %>% 
        multiply_by(-1) %>%
        max.col )
#[[1]]
#[1] 1 1 1

#[[2]]
#[1] 2 2 2

Or using base R

do.call(Map, c(f = function(...) max.col(-1 * cbind(...)), HH))
#[[1]]
#[1] 1 1 1

#[[2]]
#[1] 2 2 2

Upvotes: 1

Ronak Shah
Ronak Shah

Reputation: 388897

Maybe you can try this -

Map(function(x, y) as.integer(x > y) + 1, HH[[1]], HH[[2]])

#[[1]]
#[1] 1 1 1

#[[2]]
#[1] 2 2 2

This gives the position of the element selected.

Upvotes: 0

Related Questions