Home > front end >  How to store iterative numbered values in a list?
How to store iterative numbered values in a list?

Time:11-04

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

1000 random Lambadas 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 ??

CodePudding user response:

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

CodePudding user response:

mylist <- lapply(seq(1000), \(x) paste0("lambdaSample1_", x))

or

mylist <- list(paste0("lambdaSample1_", seq(1000)))

depending on what exactly you need. (It wasn't 100% clear to me - but one of those should do what you want.)

CodePudding user response:

I'm not sure what you have but you may try

x1 <- 1;x2 <- 2;x3 <- 3 # assuming these are already exist
xx <- paste0("x", c(1:3))


mylist <- lapply(xx,get)
names(mylist) <- xx
mylist

$x1
[1] 1

$x2
[1] 2

$x3
[1] 3

So you may try

mylist <- lapply(paste0("lambdaSample1_", c(1:1000)), get)
names(mylist) <- paste0("lambdaSample1_", c(1:1000)
  • Related