繁体   English   中英

使用 R 中的 for 循环来填充数据框以进行二项分布

[英]Using for loops in R to populate a data frame for binomial distribution

用 18 行和 2 列初始化一个名为 my_binom_loops 的空数据框。 将第一列命名为 y,将第二列命名为 pdf_y。 然后,使用嵌套循环:

  • 遍历 18 行。
  • 遍历 2 列
  • 如果内部循环位于第一列,则将 1 的增量添加到 y 列(例如 0 到 17)
  • 否则,使用 dbinom(y, size = 17, p = 0.83) 填充列 pdf_y

我不确定如何以 1 的增量填充我的第一列(y)。

# Initialize an empty data frame named my_binom_loops with 18 rows and 2 columns 
my_binom_loops <- data.frame(matrix(nrow = 18, ncol = 2))

# Name the first column y and the second column pdf_y
colnames(my_binom_loops) <- c("y", "pdf_y") 

# Iterate over the 18 rows
# Iterate over the 2 columns
y <- 0
for(rows in 1:18){
  for(cols in 1:2){
    if(cols == 1){
      y <- y + 1
      my_binom_loops$y <-  
      
    }
    
  }
}

my_binom_loops
options(scipen=99) #display not scientific notation (optional)
y=0
for(rows in 1:18){
  for(cols in 1:2){
    if(cols == 1){
      my_binom_loops[rows,cols]=y
    } else {
      my_binom_loops[rows,cols]=dbinom(y, 17, .83)
      y=y+1
    }
  }
}

每行都有 y 和 P(Y=y),其中 Y~Binomial(17,.83)。

my_binom_loops

    y                  pdf_y
1   0 0.00000000000008272403
2   1 0.00000000000686609417
3   2 0.00000000026818156067
4   3 0.00000000654678515741
5   4 0.00000011187300518994
6   5 0.00000142012908941109
7   6 0.00001386714287307294
8   7 0.00010639244910181206
9   8 0.00064930685848900134
10  9 0.00317014525026981667
11 10 0.01238221438928917111
12 11 0.03847094417206962241
13 12 0.09391436371416980733
14 13 0.17635502688407453387
15 14 0.24600785262820473731
16 15 0.24021943256636466013
17 16 0.14660450663976656860
18 17 0.04210440848131703773

暂无
暂无

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

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