在R中生成可能的序列

时间:2019-02-02 23:40:56

标签: r

我正在尝试解决R中的以下问题。通常,给定一个序列[a,b],我将从这个序列中生成一个长度为n的列表,其元素成对地至少<​​strong> >相差d。

我当时在考虑使用seq(),但是只能使用此函数创建间隔均匀的序列。

1 个答案:

答案 0 :(得分:2)

这可能就是您想要的,生成大小为n的序列中可能存在的所有可能不同值的所有排列,然后检查满足您的要求其终值为b的要求。

这对于较大的向量来说是相当密集且缓慢的,但是应该返回所有可能的有效序列(除非我犯了一个错误)。

# sequence length of n which includes a, b
# therefore need to find n - 1 values (then check that last val of cumsum == b)
#   vals must be greater than or equal to d
#   vals have upper bound is if all but one value was d, b - ((n - 1) * d)
library(gtools)
library(matrixStats)

# parameters
a = 1
b = 20
n = 5
d = 2

# possible values that differences can be
poss_diffs <- d:(b - ((n - 1) * d))

# generate all possible permutations of differences
diff_perms_n <- permutations(n = length(poss_diffs), r = n - 1, v = poss_diffs)

# turn differences into sequences, add column for the a value
seqs_n <- matrixStats::rowCumsums(cbind(a, diff_perms_n))

# filter to only valid sequences, last column == b
valid_seqs <- seqs_n[seqs_n[, ncol(seqs_n)] == b, ]

# check that diffs are all greater than d
valid_seqs_diffs <- matrixStats::rowDiffs(valid_seqs)

print(head(valid_seqs))
print(head(valid_seqs_diffs))

# > print(head(valid_seqs))
# [,1] [,2] [,3] [,4] [,5]
# [1,]    1    3    6   10   20
# [2,]    1    3    6   11   20
# [3,]    1    3    6   12   20
# [4,]    1    3    6   14   20
# [5,]    1    3    6   15   20
# [6,]    1    3    6   16   20
# > print(head(valid_seqs_diffs))
# [,1] [,2] [,3] [,4]
# [1,]    2    3    4   10
# [2,]    2    3    5    9
# [3,]    2    3    6    8
# [4,]    2    3    8    6
# [5,]    2    3    9    5
# [6,]    2    3   10    4