如果我有一个字母矢量:
> 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),我怎样才能从{{1}中选择 n 样本它的元素与all
之间有相同的非环绕间距?例如,refSample
和"a","c","d","j"
将是有效样本,但"q" "s" "t" "z"
和"a","c","d","k"
不会。前者在第3个元素和最后一个元素之间的索引差异为7(而不是6),而后者具有正确的间距但是环绕。
其次,如何对此进行参数化,以便无论使用"r" "t" "u" "a"
,我都可以使用它的间距作为模板?
答案 0 :(得分:3)
这是一个简单的方法 -
all <- letters
refSample <- c("j","l","m","s")
pick_matches <- function(n, ref, full) {
iref <- match(ref,full)
spaces <- diff(iref)
tot_space <- sum(spaces)
max_start <- length(full) - tot_space
starts <- sample(1:max_start, n, replace = TRUE)
return( sapply( starts, function(s) full[ cumsum(c(s, spaces)) ] ) )
}
> set.seed(1)
> pick_matches(5, refSample, all) # each COLUMN is a desired sample vector
[,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"