Repetition structure of a function

2

Hello! I'm having trouble finding my error in the program below. I want to generate random values from a level vector, however I want my function to return an array of generated values. My program is returning an array, but the values of the columns are the same.

For a better understanding: I have 4 levels and I want to generate 10 values for each level. My intention is to get the program to return this array of values.

Program code

 v = rep(0,4)

 for(k in 1:length(v)){


 rf = function(n,a,b,v)
   {

  u =runif(n,0,1) 

  x = (-log(u)) / (exp((b/v[k])-a))

  return(matrix(x,n,length(v))
   }

     }


  rf(10,-3,10,v=c(10,20,30,40))
    
asked by anonymous 08.09.2015 / 17:44

2 answers

3

In this case you would not need a loop either:

rf2 <- function(n, a, b, v) matrix(-log(runif(n, 0, 1)) / exp(b/rep(v, each = n)-a), 
                                   ncol = length(v))

Comparing with the Rcoster solution:

set.seed(1)
m1 <- rf(10,-3,10,v=c(10,20,30,40))
set.seed(1)
m2 <- rf2(10,-3,10,v=c(10,20,30,40))
all.equal(m1, m2)
[1] TRUE
    
08.09.2015 / 19:38
2

To achieve the expected result, for() should be within the function - and not outside:

 rf <- function(n, a, b, v) {
  u <- runif(n, 0, 1) 
  out <- matrix(0, n, length(v))
  for (k in 1:length(v)) {
      out[, k] <- (-log(u)) / (exp((b/v[k])-a))
   }
   return(out)
}

rf(10,-3,10,v=c(10,20,30,40))

I only draw attention to the line u = runif(n, 0, 1) , which depending on your goal it should go into for() .

    
08.09.2015 / 18:53