【问题标题】:Finding all permutations and calling a function on results in R在 R 中查找所有排列并在结果上调用函数
【发布时间】:2019-05-04 04:01:39
【问题描述】:

需要编写一个函数permn(m,n,FUN),它可以找到大小为 n 的 m 的所有排列,并返回一个由对每个排列调用 FUN 返回的值组成的向量,但很难弄清楚如何对每个排列调用 FUN。

由于我们不关心效率,我决定首先使用permutations() 函数计算所有排列,然后将排列向量传递给 FUN。但是,这仅适用于 FUN 不需要访问向量的特定索引的情况。

permn <- function(m, n, FUN=NULL) {
  result <- c()
  if (length(m) == 1) {
    p <- permutations(length(1:m),n,1:m)
  } else {
    p <- permutations(length(m),n,m)
  }

  result <- FUN(p)
  return(result)
}

如果我执行以下操作,permn(4,2,function(x){2*x}),则将 FUN 应用于矩阵中的每个元素,我得到正确的输出,即 12x2 矩阵。但是,传递一个应该返回每个排列的第一个元素的函数,例如 first &lt;- function(z) z[1],只返回一个元素。例如,调用 permn(7:10,2,first) 应该从一个看起来像

的矩阵返回 [1] 7 7 7 8 8 8 9 9 9 10 10 10

[1,] 7 8

[2,] 7 9

[3,] 7 10

[4,] 8 7

...

而是返回7。我怎样才能使 FUN 应用于向量中的每个排列?

【问题讨论】:

  • 你在使用来自gtools 包的permutations() 吗?
  • @andrew_reece 是的

标签: r


【解决方案1】:

您可以使用purrr::map 或base R sapply

first <- function(z) purrr::map_dbl(z[,1], ~.x[1])

# alternate
# first <- sapply(z[,1], function(x) x[1])

permn(7:10, 2, first)
#  7  7  7  8  8  8  9  9  9 10 10 10

更新每个 OP cmets
如果您需要保持first() 原样,只需将map 包裹在permn 内,如下所示:

first <- function(z) z[1]

permn <- function(m, n, FUN=NULL) {
  result <- c()
  if (length(m) == 1) {
    p <- permutations(length(1:m),n,1:m)
  } else {
    p <- permutations(length(m),n,m)
  }

  result <- purrr::map_dbl(p[,1], FUN)
  return(result)
}

permn(7:10, 2, first)
#  7  7  7  8  8  8  9  9  9 10 10 10

【讨论】:

  • 我不能编辑函数调用,它必须为first &lt;- function(z) z[1]工作
  • 你可以用map包裹FUN
  • 它不再适用于permn(4,2,function(x){2*x})
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2019-03-05
  • 1970-01-01
  • 1970-01-01
  • 2023-03-12
  • 1970-01-01
  • 2020-03-23
相关资源
最近更新 更多