如果每个独立的值都可以取相同的值(例如seq(from = 0.0001, to = 1000, by = 0.1)),我们可以更严格地处理这个问题并避免产生重复的可能性。首先,我们创建一个masterFun,它本质上是您要定义的所有函数的包装器:
masterFun <- function(y) {
## y is a vector with 6 values
## y[1] -->> x
## y[2] -->> t
## y[3] -->> v
## y[4] -->> w
## y[5] -->> n
## y[6] -->> f
fA <- function(x, t) {x * t - 2*x}
fB <- function(v, x) {v - x^2}
fC <- function(x, w, t) {x - w*t - t*t}
fD <- function(n, f, t) {(n - f)/t}
## one can easily filter out negative
## results as @jdobres has done.
c(a = fA(y[1], y[2]), b = fB(y[3], y[1]),
c = fC(y[1], y[4], y[2]), d = fD(y[5], y[6], y[2]))
}
现在,使用permuteSample,它能够生成向量的随机排列,然后将任何给定的用户定义函数应用于每个排列,来自RcppAlgos(我是作者),我们有:
## Not technically the domain, but this variable name
## is concise and very descriptive
domain <- seq(from = 0.0001, to = 1000, by = 0.1)
library(RcppAlgos)
## number of variables ... x, t, v, w, n, f
## ||
## \/
permuteSample(domain, m = 6, repetition = TRUE,
n = 3, seed = 123, FUN = masterFun)
[[1]]
a b c d
218830.316100 -608541.146040 -310624.596670 -1.415869
[[2]]
a b c d
371023.322880 -482662.278860 -731052.643620 1.132836
[[3]]
a b c d
18512.60761001 -12521.71284001 -39722.27696002 -0.09118721
简而言之,底层算法能够生成 nth lexicographical 结果,这允许我们将 1 to "# of total permutations" 的映射应用于排列本身.例如,给定向量1:3的排列:
permuteGeneral(3, 3)
[,1] [,2] [,3]
[1,] 1 2 3
[2,] 1 3 2
[3,] 2 1 3
[4,] 2 3 1
[5,] 3 1 2
[6,] 3 2 1
我们可以很容易地生成上面的 2nd 和 5th 排列,而无需生成第一个排列或前四个排列:
permuteSample(3, 3, sampleVec = c(2, 5))
[,1] [,2] [,3]
[1,] 1 3 2
[2,] 3 1 2
这使我们能够更可控、更切实地掌握随机样本,因为我们现在可以以更熟悉的方式(即随机数字样本)来思考它们。
如果您真的想查看上述计算中使用了哪些变量,我们只需删除FUN 参数:
permuteSample(domain, m = 6, repetition = TRUE, n = 3, seed = 123)
[,1] [,2] [,3] [,4] [,5] [,6]
[1,] 780.7001 282.3001 951.5001 820.8001 289.1001 688.8001
[2,] 694.8001 536.0001 84.9001 829.2001 757.3001 150.1001
[3,] 114.7001 163.4001 634.4001 80.4001 327.2001 342.1001