首页 > 解决方案 > 如何编写一个for循环来计算R中数据集每列的最大值?

问题描述

How to write a double for loop in r with selection maximum element in one loop? 中的一个类似问题?.

相同的设置:

如果我想先对 j=1,2,...,71 的 theta[j] 进行采样,然后从 Bin(n[j], theta[j]) 中复制(比如 1000 次)yrep[k], n[j] 是已知的。

对于 theta[1],我们有 yrep[1,1], yrep[1,2], ..., yrep[1,1000]。然后对于所有 theta[j],我们将有一个数据集矩阵 yrep[i,j], i=1,...,71, j=1,..,1000。然后计算均值、最大值或最小值每列 yrep[1,1], yrep[1,2], yrep[1,3], ... yrep[1,71],我们将得到 1000 个平均值,最大值或最小值。

这个for循环怎么写?

我首先尝试编写一个循环来采样 theta[j] 和 yrep。我不知道如何添加代码来计算此循环中的最大值、平均值和最小值。我不确定这段代码是否正确:

theta<-NULL
yrep<-NULL
test<-NULL
k=1
for(i in 1:1000){
  for(j in 1:71){
    theta[j] <- rbeta(1,samp_A+y[j], samp_B+n[j]-y[j])
    yrep[k]<-rbinom(1, n[j], theta[j])
    k=k+1
  }
  t<-c(test, max(yrep))
}

数据在如何在一个循环中选择最大元素的情况下在 r 中编写一个双循环?

   #Data
  y <- c(0,0,0,0,0,0,0,0,0,0,0,0,0,0,1,1,1,1,1,1,1,1,2,2,2,2,2,2,2,2,
   2,1,5,2,5,3,2,7,7,3,3,2,9,10,4,4,4,4,4,4,4,10,4,4,4,5,11,12,
   5,5,6,5,6,6,6,6,16,15,15,9,4)
  n <- 
   c(20,20,20,20,20,20,20,19,19,19,19,18,18,17,20,20,20,20,19,19,18,18,25,24,
   23,20,20,20,20,20,20,10,49,19,46,27,17,49,47,20,20,13,48,50,20,20,20,20,
   20,20,20,48,19,19,19,22,46,49,20,20,23,19,22,20,20,20,52,46,47,24,14)


  #Evaluate densities in grid
  x <- seq(0.0001, 0.9999, length.out = 1000)


  #Compute the marginal posterior of alpha and beta in hierarchical model Use grid

  A <- seq(0.5, 15, length.out = 100)
  B <- seq(0.3, 45, length.out = 100)

  #Make vectors that contain all pairwise combinations of A and B

  cA <- rep(A, each = length(B))
  cB <- rep(B, length(A))

 #Use logarithms for numerical accuracy!

 lpfun <- function(a, b, y, n) log(a+b)*(-5/2) +
  sum(lgamma(a+b)-lgamma(a)-lgamma(b)+lgamma(a+y)+lgamma(b+n-y)- 
   lgamma(a+b+n))
lp <- mapply(lpfun, cA, cB, MoreArgs = list(y, n))

 #Subtract maximum value to avoid over/underflow in exponentiation

 df_marg <- data.frame(x = cA, y = cB, p = exp(lp - max(lp)))

 #Sample from the grid (with replacement)

  nsamp <- 100
  samp_indices <- sample(length(df_marg$p), size = nsamp,
                   replace = T, prob = df_marg$p/sum(df_marg$p))
  samp_A <- cA[samp_indices[1:nsamp]]
  samp_B <- cB[samp_indices[1:nsamp]]
   df_psamp <- mapply(function(a, b, x) dbeta(x, a, b),
               samp_A, samp_B, MoreArgs = list(x = x)) %>%
   as.data.frame() %>% cbind(x) %>% gather(ind, p, -x)

标签: r

解决方案


这没有经过很好的测试。
循环不需要从包含在基础 R 中的分布中进行采样,这些函数是根据它们的参数向量化的。遵循以下几行的代码应该能够完成问题的要求。

Ni <- 1000
Nj <- 17

theta <- rbeta(Ni*Nj, rep(samp_A + y, each = Ni), rep(samp_B + n - y, each = Ni))
yrep <- rbinom(Ni*Nj, n, theta)
test1 <- matrix(yrep, nrow = Ni)
mins1 <- matrixStats::colMins(test1)

推荐阅读