Store values in For Loop

后端 未结 2 871
没有蜡笔的小新
没有蜡笔的小新 2020-12-10 09:01

I have a for loop in R in which I want to store the result of each calculation (for all the values looped through). In the for loop a function is called and the output is st

相关标签:
2条回答
  • 2020-12-10 09:29

    To get a list of results:

    n = 3
    lapply(1:n, function(par1) {
      # your function and whatnot, e.g.
      par1*par1
    })
    

    Or sapply if you want a vector instead.

    A bit more complicated example:

    n = 3
    some_fn = function(x, y) { x + y }
    
    par2 = 4
    lapply(1:n, function(par1) {
      var = some_fn(par1, par2)
      return(c(var, par1))  # don't have to type return, but I chose to make it explicit here
    })
    #[[1]]
    #[1] 5 1
    #
    #[[2]]
    #[1] 6 2
    #
    #[[3]]
    #[1] 7 3
    
    0 讨论(0)
  • 2020-12-10 09:32

    initialise an empty object and then assign the value by indexing

    a <- 0
    for (i in 1:10) {
         a[i] <- mean(rnorm(50))
    }
    
    print(a)
    

    EDIT:

    To include an example with two output variables, in the most basic case, create an empty matrix with the number of columns corresponding to your output parameters and the number of rows matching the number of iterations. Then save the output in the matrix, by indexing the row position in your for loop:

    n <- 10
    mat <- matrix(ncol=2, nrow=n)
    
    for (i in 1:n) {
        var1 <- function_one(i,par1)
        var2 <- function_two(i,par2)
        mat[i,] <- c(var1,var2)
    }
    
    print(mat)
    

    The iteration number i corresponds to the row number in the mat object. So there is no need to explicitly keep track of it.

    However, this is just to illustrate the basics. Once you understand the above, it is more efficient to use the elegant solution given by @eddi, especially if you are handling many output variables.

    0 讨论(0)
提交回复
热议问题