gpt4 book ai didi

r - 使用样本列表作为模板从带有环绕的较大列表中进行采样

转载 作者:行者123 更新时间:2023-12-04 05:47:53 27 4
gpt4 key购买 nike

类似于我在 Using a sample list as a template for sampling from a larger list without wraparound 的问题,我怎么知道这样做允许环绕?

因此,如果我有一个字母向量:

> all <- letters
> all
[1] "a" "b" "c" "d" "e" "f" "g" "h" "i" "j" "k" "l" "m" "n" "o" "p" "q" "r" "s" "t" "u" "v" "w" "x" "y" "z"

然后我从字母中定义一个引用样本,如下所示:
> refSample <- c("j","l","m","s")

其中元素之间的间距为 2(第 1 到第 2)、1(第 2 到第 3)和 6(第 3 到第 4),然后我如何从 all 中选择 n 个样本其元素之间具有相同的环绕间距到 refSample ?例如, "a","c","d","j" , "q" "s" "t" "z""r" "t" "u" "a"将是有效的样本,但 "a","c","d","k"不会。

同样,为函数设置参数是最好的。

最佳答案

我会把它留作练习,但这里是——

all <- letters                                                                                                                                                                                                                                                                
refSample <- c("j","l","m","s")

pick_matches <- function(n, ref, full, wrap = FALSE) {
iref <- match(ref,full)
spaces <- diff(iref)
tot_space <- sum(spaces)
N <- length( full ) - 1
max_start <- N - tot_space*(1-wrap)
starts <- sample(0:max_start, n, replace = TRUE)
return( sapply( starts, function(s) full[ 1 + cumsum(c(s, spaces)) %% (N+1) ] ) )
}


> set.seed(1)



> pick_matches(5, refSample, all, wrap = FALSE)
[,1] [,2] [,3] [,4] [,5]
[1,] "e" "g" "j" "p" "d"
[2,] "g" "i" "l" "r" "f"
[3,] "h" "j" "m" "s" "g"
[4,] "n" "p" "s" "y" "m"

> pick_matches(5, refSample, all, wrap = TRUE)
[,1] [,2] [,3] [,4] [,5]
[1,] "x" "y" "r" "q" "b"
[2,] "z" "a" "t" "s" "d"
[3,] "a" "b" "u" "t" "e"
[4,] "g" "h" "a" "z" "k"

关于r - 使用样本列表作为模板从带有环绕的较大列表中进行采样,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/10441185/

27 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com