我想随机在1到15之间为我的起始位置向量中的每个元素添加一个随机数(每个元素的随机抽取),并且我从不希望任何元素在彼此的4个或更少之内(例如,如果一个元素=到20然后我不希望下一个元素低于25)。我所写的内容是否已经完成,并且有更好的方法吗?
startingpositions <- c(seq(5, 110-15, 15),seq(115, 220-15, 15),seq(225, 330-15, 15),seq(335, 440-15, 15))
positions <- c()
x <- 0
for (j in startingpositions)
# for each element of my vector
{
sub.samples <- setdiff(1:15 + j, seq(x-4,x+4,1))
# create the list of numbers it's ok to draw from (based on x which is = to my previous element). Only draw from numbers 4> than x
x <- sample(sub.samples, 1)
# create new x for my current element from sub samples
positions <- c(positions,x)
#add x to my positions vector
}
答案 0 :(得分:1)
声明startingpositions
,然后沿着以下行运行一个短循环,这应该有效。
for(i in 1:length(startingpositions))
{
startingpositions[i] <- max(startingpositions[i] + round(runif(1, 1, 15),0), startingpositions[i-1] + 4)
}