Home > Software engineering >  How to apply a function that depends on three variables in R?
How to apply a function that depends on three variables in R?

Time:12-12

Im sure a question like this has been asked before. But Im struggling to find an answer (and to even word the question clearly).

If I have 2 variables, I want to apply a function to each pair of these variables, where the function depends on a third variable. For example,

If I have some data that looks like this:

x <- c(1:4)
y <- c(1,2)
n <- seq(1,200, length.out = 100)

Now, imagine I want to apply rnorm to each of the pairs of x and y, where y would be my mean and x would be the standard deviation. But I want to loop through each of these pairs where each value of n would be my number of observations.

So for example, I was trying a nested loop... the below example doesn't work, but I hope it illustrates what Im trying to achieve:

for(i in 1:2){
  for(j in 1:4){
    for(k in 1:length(n)){
    ans[] <- rnorm(n[k], y[i], x[j])
    }
  }
}

Any suggestions as to how I could achieve this?

CodePudding user response:

using expand.grid

z = expand.grid(n,x,y)
apply(z, 1, function(i) rnorm(i[1], i[2], i[3]))
  •  Tags:  
  • r
  • Related