Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

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:

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

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?

>Solution :

using expand.grid

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

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading