【问题标题】:Sort list of arrays in RR中的数组列表排序
【发布时间】:2018-10-16 08:37:18
【问题描述】:

我有一个数组列表,我想选择最好的数组(最好的意思是那个数组中所有值之和最小的数组)。

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)

有什么功能可以做到吗? 我需要在这样一个循环中做:

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)
  }
}

您认为每次从我的列表中找到“最佳”值更好,还是先排序列表然后选择第一个元素?

【问题讨论】:

  • 那么,如果我正确理解了这个问题,你需要一个pickBestFrom 函数吗?

标签: arrays r sorting


【解决方案1】:

如果我上面的评论是正确的,即,你需要一个pickBestFrom 函数那么这里有两种选择,用代码来计时。

首先对总和进行排序,然后选择最小的列表成员。
第二个使用which.min选择较小的和,速度更快。

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
)

第二次测试,列表更大。 which.min 仍然是最快的。

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

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

【讨论】:

    猜你喜欢
    • 2014-05-03
    • 2011-07-16
    • 2011-05-01
    • 2018-01-04
    • 2011-05-21
    • 2020-01-06
    • 1970-01-01
    • 2014-06-04
    相关资源
    最近更新 更多