[英]R Limit matrix in random walk
I have the following code for a random walk, in which I start from i
and add up cumulatively for each line.我有以下用于随机游走的代码,其中我从
i
开始并为每一行累加。
However, I need to limit my random walk on each line.但是,我需要限制我在每条线上的随机游走。 One way I thought of doing this, would be from the index
j
(where the value in the position is less than or equal to 0 or greater than or equal to t
) of each line replace with null.我想到的一种方法是从索引
j
(其中 position 中的值小于或等于 0 或大于或等于t
)的每一行替换为 null。
simulate_binomial = function(cenarios, rodadas, p){
return(matrix(data=rbinom(cenarios*rodadas, 1, p), nrow=cenarios, ncol=rodadas))
}
i = 2
t = 10
p = 0.8
max_walk = 100
samples = simulate_binomial(1000, max_walk, p)
samples[samples==0] = -1
walk = t(apply(cbind(i, samples), 1, cumsum))
walk1 = apply(walk, 1, function(x) (which((x <= 0) | (x >= t))[1]))
So my walk1
would be the indices of each line that would have a value less than or equal to zero or greater than or equal to t
.所以我的
walk1
将是每行的索引,这些行的值将小于或等于零或大于或等于t
。 However, I don't know how to assign null for this index onwards in the line.但是,我不知道如何在行中为这个索引分配 null。
My intention is to assign null so that I can plot precisely without this null part and see the effect of the ruin on each line / "scenario".我的意图是分配 null 这样我就可以在没有这个 null 部分的情况下精确地 plot 并查看废墟对每一行/“场景”的影响。
Can anyone help me plz?谁能帮我吗?
You can change your last apply
to:您可以将上次
apply
更改为:
walk1 <- t(apply(walk, 1, function(x) {
inds <- (which((x <= 0) | (x >= t))[1])
x[(inds+1):length(x)] <- NA
x
}))
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.