在向量上运行随机运算,条件

时间:2018-01-26 06:24:04

标签: r random

我正在做一些建模并希望模拟随机性。

在此示例中,我的总运行次数run_times5。 持有run_lengths的向量将打印1,因此如果运行长度为3,则会打印1 3次。 sample_data包含10的样本。在1时随机执行run_lengths sample_data == 1的打印应用。不是所有== 1都要被挑选。只有随机...和操作才能打印1,总数为run_times(5)。

肯定会有一些活动部件。

我正在以这种方式解决问题:

我可以随run_lengths随机选择sample(run_lengths, 1)。我不确定如何随机选择sample_data,而我正试图保留一个计数器,以便留在run_times下:

run_lengths <- c(2,4,5,6,7,8,1)
run_times <- 5
sample_data <- c(0,0,0,0,0,0,0,1,1,1,1,1,1,1,1,1,1,1,1,1,0,0,0,0,0,0,0,0,0,0,0,1,1,1,1,1,1,1,1,1,1,1,0,0,0,0,0,0,1,1,1,1,0,0,0,0,0,0,0,0,1,1,1,1,0,0,0,0,0,0)
# Randomly select 1's from sample_data, when find 1, randomly print 1's along run_lengths 
# Only print a certain amount of times (run_times)
# Pick run_lengths at random == sample(run_lengths,1)
# Pick df$sample 1's at random, how to randomly select????

count <- 0  # keep track of how many random run_lengths is being applied
res <- NULL
while (length(res) < length(sample_data)) {
   if (sample_data[length(res)+1] == 1 & count < run_times) { # not sure how to pick sample_date == 1?
   res <- c(res, rep(1,sample(run_lengths,1)))   # if signal == 1 (randomly) then randomly rep a run_length
   count <- count +1  # count how many random reps, run_lengths have been applied
   } else {
     res <- c(res, 0)  # Note if condition is not true, we print 0 vs 1
   }
}
res <- res[1:length(sample_data)]
res

我完成了它可能是60%?我不确定从sample_data中选择随机1的最佳方法是什么。另外,我不确定如何仅将run_lengths的数量保持在最大run_times之下。当条件成立时,我试图保持count。如果超过它,它将忽略任何其他真实条件。

1 个答案:

答案 0 :(得分:0)

好的,是时候放下一些代码了,还是不确定它是否正确

sample_data <- c(0,0,0,0,0,0,0,1,1,1,1,1,1,1,1,1,1,1,1,1,0,0,0,0,0,0,0,0,0,0,0,1,1,1,1,1,1,1,1,1,1,1,0,0,0,0,0,0,1,1,1,1,0,0,0,0,0,0,0,0,1,1,1,1,0,0,0,0,0,0)

# take indices of of sampled data where value == 1
i <- which(sample_data %in% 1)

# now shuffle them all, no replacement - random positions with 1s
p <- sample(i, length(i), replace=FALSE)

print(sample_data[p[1]])
print(sample_data[p[2]])
print(sample_data[p[3]])
...

这是你想要的吗?