Branislav Kramár
Branislav Kramár

Reputation: 13

Sort list of arrays in R

I have list of arrays and I want to pick up the best array (best means that one, which has smallest sum of all values inside the array).

v1 = c(5,5,5,5)
v2 = c(6,6,6,6)
v3 = c(7,7,7,7)
v4 = c(8,8,8,8)
v5 = c(1,1,1,1)
v6 = c(2,2,2,2)
v7 = c(3,3,3,3)
v8 = c(4,4,4,4)
arr1 = array(c(v1,v2,v3,v4), dim = c(4,4))
arr2 = array(c(v5,v6,v7,v8), dim = c(4,4))
myList = list(arr1,arr2)

Is there any function that can do it? I need to do it in such a loop:

solve <- function() {
  A <- myList
  while(length(A) != 0) {
    X <- pickBestFrom(A)
    if(isSolution(X)){
      return(X)
      break
    }
    Y <- neighbors(X)
    A <- append(A,Y)
    A <- unique(A)
  }
}

Do you think it is better to find each time "best" value from my list, or to order the list first and then pick the first element?

Upvotes: 0

Views: 82

Answers (1)

Rui Barradas
Rui Barradas

Reputation: 76673

If my comment above is right, i.e., you need a pickBestFrom function then here are two alternatives, with code to time them.

The first sorts the sums and then chooses the smallest list member.
The second chooses the smaller sum using which.min and is faster.

pickBestFrom1 <- function(X){
    X[[ order(sapply(X, sum))[1] ]]
}

pickBestFrom2 <- function(X){
    X[[which.min(sapply(X, sum))]]
}

microbenchmark::microbenchmark(
    order = pickBestFrom1(myList),
    which.m = pickBestFrom2(myList),
    times = 1e3
)

Second test, with a larger list. which.min is still the fastest.

list2 <- lapply(1:1000, function(i) array(rnorm(16), dim = c(4, 4)))

microbenchmark::microbenchmark(
    order = pickBestFrom1(list2),
    which.m = pickBestFrom2(list2),
    times = 1e3
)

Upvotes: 1

Related Questions