rlistfunction

How to store iterative numbered values in a list?


I have iterative numbered values lambdaSample1_1, lambdaSample1_2, lambdaSample1_3.... lambdaSample1_1000.

# 1000 random lambdas for dataset 3
  
for (i in 1:numSamples) {
    # generate ramdomNumber for credible interval
    randomNumber <- floor(runif(numSamples, min = 1, max = nrow(mcmcMatrix)))
    assign(paste0("lambdaSample3_", i), mcmcMatrix[randomNumber[[i]], lambdas[[3]]])
}

I got lambdaSample3_1 ~ lambdaSample3_1000 from the Matrix that has 60000 rows by randomly selecting the values using randomnumbers from 1 ~ 1000.

Now what I like to do is to combine the generated values "lambda1_1" ~ "lambda1_1000" into a single list

I would like to store 1,000 values in one single list. Is there any way that I can write a simple code rather than writing 1,000 values into a list?

mylist <- list(lambdaSample1_1, lambdaSample1_2 ,,,,, lambdaSample1_1000) 

for (i in 1:numSamples) {
    # generate ramdomNumber for credible interval
    randomNumber <- floor(runif(numSamples, min = 1, max = nrow(mcmcMatrix)))
    assign(paste0("lambdaSample3_", i), mcmcMatrix[randomNumber[[i]], lambdas[[3]]])
}

How can I make this type of list without writing down 1000 times of lambdaSample1_x ??


Solution

  • Untested code since your question is not reproducible, but something similar to

    lamdaSamples1 <- lapply(
                        floor(runif(numSamples, min = 1, max = nrow(mcmcMatrix))),
                        function(x) mcmcMatrix[x, lambdas[[3]]]
                      )
    

    Will avoid the problem entirely by adding your objects to a list in the first place.

    lapply works by applying the function in its second argument to all values in its first agrument in turn. Its return value is a list.

    So, as a simple example, to obtain a list of the first three squares, we can write

    lapply(1:3, function(x) x*x)
    [[1]]
    [1] 1
    
    [[2]]
    [1] 4
    
    [[3]]
    [1] 9