0
我想隨機地在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
}
您可以在代碼中添加註釋來解釋您期望您的語句在做什麼嗎?這將更容易解釋你可能錯在哪裏。 – TheComeOnMan
好的,我已經完成了。乾杯 – luke123