Repeating structure of a function

Asked

Viewed 379 times

2

Hello! I am having trouble finding my error in the program below. I want to generate allele 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 column values are equal.

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

Code of the program

 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))

2 answers

3


In that case you wouldn’t 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 to 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

2

To achieve the expected result, the 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 just draw attention to the line u = runif(n, 0, 1), that depending on your goal it should go into the for().

Browser other questions tagged

You are not signed in. Login or sign up in order to post.