简体   繁体   中英

How to apply a function that depends on three variables in R?

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?

using expand.grid

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

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM