Home > OS >  Iterative multiplication of the two lists in R
Iterative multiplication of the two lists in R

Time:11-05

I am trying to multiply the values stored in a list containing 1,000 values with another list containing ages. Ultimately, I want to store 1,000 rows to a dataframe. I wonder if it's better to use lapply fucntion or for loop function here.

list 1

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

*the out put is 1,000 different values in a list. *

list 2

ager1= 14:29

What I want to do is

  for (i in 1: numSamples) {
  assign(paste0("newRow1_", i), 1-exp(-lambdaSample1[[i]]*ager1))
   }

now I got 1,000 rows of values that I want to store in a predetermiend dataframe, outDf_1 (nrow=1000, ncol = ager1).

I tried

`

  for (i in 1:numSamples) {
    
    outDf_1[i,] <- newRow1_i
    
  }
  

I want to store newRow1_1, ,,,,,, , newRow1_1000 to each of the 1,000 row of outDf_1 dataframe.

SHould I approach different way?

CodePudding user response:

I think you're overcomplicating this a bit. Many operations in R are vectorized so you shoudln't need lapply or for loops for this. You didn't give us any data to work with but the code below should do what you want in a more straightforward and fast way.

lambdaSamples1 <- mcmcMatrix[sample(nrow(mcmcMatrix), numSamples, replace=T), 
                             lambdas[[1]]]
outDF_1 <- 1 - exp(-lambdaSamples1 %*% t(ager1))

Just note that this makes outDF_1 a matrix, not a data frame.

  • Related