rnorouzian
rnorouzian

Reputation: 7517

for loop that repeats a different combination of the argument values of an R function

Background:

I have a function called "Dist" (please see R below). This function takes 3 arguments. First, type can be either "cauchy" or "normal". Second, width can be ".5", ".707", or "1". Third, half can be TRUE or FALSE.

Coding question:

I'm wondering how to form a for loop so that at each run (repetition), I can get a different combination of the 3 argument values used in the function?

NOTE 1: This question might be similar to tossing 3 objects, 2 of which have 2 sides, and one has 3 sides. I'm asking how a for loop should be set up so that at each toss different sides of the 3 objects are considered by the loop.

NOTE 2: I need this to be ONLY a for loop so I can create png files for each "i".

Dist = function(type, width, half) {   ## START of the Function

if(type == "normal" & half == F){ 

curve(dnorm(x, 0, width), -6, 6) 

} else if (type == "cauchy" & half ==F) { 

curve(dcauchy(x, 0, width), -6, 6) 

} else if (type == "normal" & half){ curve(dnorm(x, 0, width), 0, 6)

} else { curve(dcauchy(x, 0, width), 0, 6) }

}                                     ## END of the function

####### Test the function above Here:

Dist(type ="cauchy", width = 1, half = F)

####### A for loop for the function above (not working correctly):

for (i in 1:10) {

   ww = c(rep(sqrt(2)/2, 5), rep(1, 5))[i]
   GG = c(rep(FALSE, 5), rep(TRUE, 5))
   DD = c(rep("cauchy", 5), rep("normal", 5))

  Dist(typ = DD, width = ww, half = GG)

  Sys.sleep(1/2)
   }

Upvotes: 0

Views: 127

Answers (2)

user6621347
user6621347

Reputation:

I'm going to give a hint at what you need to do. Basically, your question is a combinometeric question. If you run your loop knowing what values from one argument are going to interact with what values from another argument, you get a fine for loop.

For simplicity's sake, I pick 2 arg. values from your function and thus will be 2^3 (i.e., 8) unique situations.

So, your loop will look like this (and you can achieve "i" png files):

for (i in 1:8) {

   type = c(rep("cauchy", 4), rep("normal", 4) )[i]
  width = rep(c(1, sqrt(2)/2), 4)[i]
   half = c(rep(F, 2), rep(T, 2), rep(F, 2), rep(T, 2) )[i]

  Dist(type = type, width = width, half = half)

  Sys.sleep(1)

  }

Upvotes: 0

baptiste
baptiste

Reputation: 77096

here's an example,

Dist = function(type, width, half) {  
  paste("type:", type,"width:", width, "half:", half, sep="")
}


args <- expand.grid(type = c("normal", "cauchy"),
                    width = 1:3, 
                    half = c(TRUE, FALSE))

plyr::mdply(args, Dist)

Upvotes: 1

Related Questions