for循环重复R函数的参数值的不同组合

时间:2017-04-18 06:19:03

标签: r function for-loop

背景

我有一个名为“ Dist ”的功能( 请参阅下面的R )。该函数有3个参数。 首先, type可以是“柯西”或“正常”。 其次, width可以是“.5”,“。707”或“1”。 第三, half可以是TRUE或FALSE。

编码问题:

我想知道如何形成一个 for循环,以便在每次运行(重复)时,我可以得到一个不同的co mbination中使用的3个参数值功能?

注1:这个问题可能类似于抛掷3个对象,其中2个有2个边,1个有3个边。我问的是如何设置for循环,以便在每次折腾时loop都会考虑3个对象的不同边。

注2:我需要只能for循环,因此我可以为每个“i”创建png个文件。< / p>

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

2 个答案:

答案 0 :(得分:1)

这是一个例子,

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)

答案 1 :(得分:0)

我要暗示你需要做什么。基本上,你的问题是一个组合问题。如果你运行你的循环知道一个参数中的哪些值将与另一个参数中的值进行交互,那么你得到一个很好的for循环。

为了简单起见,我挑选2个arg。来自你的函数的值,因此将是2 ^ 3(即8)个独特的情况。

所以,你的循环看起来像这样(你可以实现&#34;我&#34; png文件):

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)

  }