简体   繁体   English

R中用于分区的双循环

[英]Double Loop for partitioning in R

How do you write a double loop partitioning a set of probability values. 如何编写对一组概率值进行分区的双循环。

First, I generated the probability values 首先,我生成了概率值

pval <- function(n, pr, mu1, mu2, Sigma)
{  x <- rep(NA,n)
for(j in 1:n)
  { n1 <- rbinom(1,1,pr)                     
   if (n1) 
  x[j] <- rnorm(1,mu1, Sigma)  else          
  x[j] <- rnorm(1,mu2, Sigma)                 
p <- pnorm(x, lower.tail=F)                
}
return(p)
}

n <- 100; pr <-0.25; mu1=0, mu2=1, Sigma 1
u1 <- pval(100, 0.25,0,1,1)                 
u1

u1 is the prob. u1是概率。 values. 值。 Here is partitioning code 这是分区代码

k <- 3

y=matrix(data=NA, nrow=n, ncol=k)


for(i in 1:n){
 for(j in 1:k){

 if (u1 > (j-1)/k  & u1 < j/k) 
 y[i,j] <- 1     else 
 y[i,j] <- 0 

 }
}
y

but something seems to be wrong with my code 'cos I have the same partitions 但是我的代码似乎有点问题,因为我有相同的分区

 [96,]    0    1    0
 [97,]    0    1    0
 [98,]    0    1    0
 [99,]    0    1    0
 [100,]   0    1    0

Can anyone spot what's wrong here? 有人可以在这里发现问题吗?

As you are using a for loop, you are comparing one element at a time, and entering them one-by-one into y . 在使用for循环时,您一次比较一个元素,并将它们一个一地输入y

Try using this as your partition function: 尝试将其用作分区函数:

for(i in 1:n){
  for(j in 1:k){

    if ((u1[i] > (j-1)/k)  && (u1[i] < j/k) )
      y[i,j] <- 1     else 
        y[i,j] <- 0 

  }
}

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM