R:查找X的范围
我将X的值分成5个框,并计算其联合概率 在下面的例子中,因为X中有很多2,所以最后我只有4个盒子 例如:R:查找X的范围,r,R,我将X的值分成5个框,并计算其联合概率 在下面的例子中,因为X中有很多2,所以最后我只有4个盒子 例如: X <-c(1,2,2,2,2,3,4,5,6,7) Y <-c(0,1,1,1,0,1,0,1,0,1) qX=quantile(X, 1:4/5) # find quantiles 20%,40%,60%,80% qY=c(0,1) dX=findInterval(X,qX,rightmost.closed=TRUE) dY=findInterval(Y,qY+0.001,
X <-c(1,2,2,2,2,3,4,5,6,7)
Y <-c(0,1,1,1,0,1,0,1,0,1)
qX=quantile(X, 1:4/5) # find quantiles 20%,40%,60%,80%
qY=c(0,1)
dX=findInterval(X,qX,rightmost.closed=TRUE)
dY=findInterval(Y,qY+0.001,rightmost.closed=TRUE)
pXY=xtabs(~dX+dY)/10 # joint distribution
rownames(pXY) <- paste("box",1:dim(pXY)[1],sep="")
> pXY
dY
dX 0 1
box1 0.1 0.0
box2 0.1 0.4
box3 0.1 0.1
box4 0.1 0.1
xtabs
或table
的输出有点混乱。我将转换为矩阵:
pXY2 <- pXY; class(pXY2) <- "matrix"
data.frame(r=t(sapply(split(X,dX),range)),pXY2)
# r.1 r.2 X0 X1
# 0 1 1 0.1 0.0
# 2 2 3 0.1 0.4
# 3 4 5 0.1 0.1
# 4 6 7 0.1 0.1
您声明了所需的输出,然后发布了实现输出的代码。你的问题是什么?我只想在每个框中增加一列X的范围。底部的pXY不提供X的范围。
pXY2 <- pXY; class(pXY2) <- "matrix"
data.frame(r=t(sapply(split(X,dX),range)),pXY2)
# r.1 r.2 X0 X1
# 0 1 1 0.1 0.0
# 2 2 3 0.1 0.4
# 3 4 5 0.1 0.1
# 4 6 7 0.1 0.1
brackem <- function(x) paste0("[",x[1],",",x[2],"]")
data.frame(r=tapply(X,dX,function(z)brackem(range(z))),pXY2)
# r X0 X1
# 0 [1,1] 0.1 0.0
# 2 [2,3] 0.1 0.4
# 3 [4,5] 0.1 0.1
# 4 [6,7] 0.1 0.1