我正在尝试从此创建一个条件概率矩阵:
我已经重写了没有循环的代码
a # Signal Vector
b # Price Change Vector
Signalt<- seq(0, 1, 0.05) # Produce the 5% tiles
abst <- c(seq(1, 1.02, by = 0.0025), 2) #Produce the 0% to 2% tiles with 0.25% increments. Added 1 to include price change of 0 in `temp`
xbool = ((Signal >= Signalt[1] & a < Signalt[1 + 1]) *1) # 1 for True 0 for False
temp = (PercChange + 1) * xbool
temp2 <- temp[which(temp > 0)]
CondProb <- cut(temp2, abst, include.lowest = T)
table(CondProb)
这将输出带有出现列数的表格。 我当然需要它在每行总数的百分比,但我想首先能够运行循环并获得矩阵输出。
循环原始 - 应该在很大程度上忽略,因为我已经改变了大部分编码设置
Signal <- runif(100)
PercChange <- abs((rnorm(100)/100))
signalt <- seq(0, 1, 0.05)
abst <- seq(0, c(0.02:1), 0.0025)
CondDistMat <- matrix(0, nrow = length(signalt), ncol = length(abst))
for(j in 1:length(signalt - 1)){
xbool = (is.na((Signal >= signalt[j] & Signal < signalt[j + 1]) ) * 1)
ysubset = (PercChange * xbool[j] )
CondProb = hist(ysubset, breaks = abst, freq = TRUE)
CondDistMat[signalt, abst] <- CondProb$density
}
列将是abst
定义的百分位数,而行将是signalt
定义的5%切片。这个想法是通过布尔向量来产生1&#39; s,其中绝对返回PercChange
应该在列中,然后绘制每个signalt
的概率。
然而,我无法产生输出 - 有人能发现错误吗? 提前致谢
所需的输出应该与附加图像类似。
答案 0 :(得分:1)
听起来你想要cut
或findInterval
使用这些函数输出的示例
> cut(rnorm(9), breaks = -6:6)
[1] (0,1] (-2,-1] (0,1] (1,2] (0,1] (-1,0] (-2,-1] (0,1] (-1,0]
12 Levels: (-6,-5] (-5,-4] (-4,-3] (-3,-2] (-2,-1] (-1,0] (0,1] (1,2] ... (5,6]
> findInterval(rnorm(9), -6:6)
[1] 7 6 7 6 8 9 7 7 6