避免循环生成具有嵌套列表的复杂数据帧

时间:2016-06-03 19:04:10

标签: r list loops dataframe

这是一种DF,我必须生成存储模拟数据。)

    nbSimul         <- 100
    nbSampleSizes   <- 4
    nbCensoredRates <- 4
    sampleSize      <- c(100, 50, 30, 10)
    censoredRate    <- c(0.1, 0.3, 0.5, 0.8)

    df.sampled      <- data.frame(cas              = numeric()  ,
                                  distribution     = character(),
                                  simul            = numeric()  ,
                                  sampleSize       = numeric()  ,
                                  censoredRate     = numeric()  ,
                                  dta              = I(list())  ,
                                  quantileLD       = I(list())  ,
                                  stringsAsFactors = FALSE)

    v <- 0  # Scenario indicator
    for(k in 1:nbCensoredRates){
         for(j in 1:nbSampleSizes){
              for(i in 1:nbSimul){

                   # Scenario Id + Other info
                   v <- v + 1
                   df.sampled[v,"cas"]   <- v
                   df.sampled[v,"distribution"] <- "logNormal"
                   df.sampled[v,"simul"]        <- i
                   df.sampled[v,"sampleSize"]   <- sampleSize[j]
                   df.sampled[v,"censoredRate"] <- censoredRate[k]

                   X <- rlnorm(sampleSize[j], meanlog = 0, sdlog = 1)

                   estimatedLD <- array(9)
                   for(w in 1:9){
                        estimatedLD[w] <- quantile(X, probs=censoredRate[k], type=w)[[1]]
                   }

                   df.sampled$dta[v]             <- list(X)
                   df.sampled$quantileLD[v]      <- list(estimatedLD[1:9])
              }
         }
}

这很难理解。
我想找到一种方法来避免循环,并轻松引用场景(v)和附加变量 有什么想法吗?

0 个答案:

没有答案