Building a list in a loop in R - getting item names correct

后端 未结 3 2156
挽巷
挽巷 2020-12-13 09:49

I have a function which contains a loop over two lists and builds up some calculated data. I would like to return these data as a lists of lists, indexed by some value, but

3条回答
  •  谎友^
    谎友^ (楼主)
    2020-12-13 10:36

    To show that an explicit for loop is not required

    unif_norm  <- replicate(5, list(uniform = runif(10),
      normal = rnorm(16)), simplify=F)
    
    binomials <- lapply(seq_len(5)/10, function(prob) {
     list(binomial =  rbinom(n = 5 ,size = 8, prob = prob))})
    
    biglist <- setNames(mapply(c, unif_norm, binomials, SIMPLIFY = F), 
                         paste0('item:',seq_along(unif_norm)))
    

    In general if you go down the for loop path it is better to preassign the list beforehand. This is more memory efficient.

    mybiglist <- vector('list', 5)
    names(mybiglist) <- paste0('item:', seq_along(mybiglist))
    for(i in seq_along(mybiglist)){
        a <- runif(10)
        b <- rnorm(16)
        c <- rbinom(8, 5, i/10)
    
        tmp <- list(uniform=a, normal=b, binomial=c)
        mybiglist[[i]] <- tmp
    }
    

提交回复
热议问题