Search code examples
rlapplysapply

Find minimum of List of Lists in R


I have a list of lists. I want to get the order_number with the smallest distance.

Here's my list of lists.

d <- list( list(distance = 450, order_number = 12), 
list(distance = 930, order_number = 99), 
list(distance = 100, order_number = 34))

The order_number with the smallest distance is 34.

Here's what I have so far.

sapply(d, function(x) d[which.min(d[[x]]$distance,]$order_number))

which gives a syntax error.


Solution

  • Try this:

    df = as.data.frame(do.call(rbind, lapply(d, unlist)))
    df$order_number[df$distance==min(df$distance)]
    

    This returns the order_number where distance is minimum