生成R中可能的序列

问题描述 投票:-1回答:1

我试图解决在R.一般地存在以下问题,给定的序列[A,B],我这个序列具有一个长度为n,其元素成对地至少有d的差生成列表。

我的想法是使用了序列(),但你只能创建使用此功能均匀间隔序列。

r
1个回答
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
© www.soinside.com 2019 - 2024. All rights reserved.