背景:
我有一个名为"Dist“的函数(请参见下面的R)。此函数采用3个参数。首先, type可以是"cauchy“,也可以是"normal”。第二, width可以是".5“、".707”或"1“。第三, half可以是对的,也可以是假的。
编码问题:
我想知道如何形成for循环,以便在每次运行(重复)时,可以得到函数中使用的3个参数值的不同的协同混合。
注1:这个问题可能类似于抛出3个对象,其中两个有两个边,一个有三个边。我在问如何设置一个for循环,以便在每次抛出时,loop都会考虑3个对象的不同侧面。
注释2:--我需要这样做才能使成为一个循环,这样我就可以为每个"i“创建png文件。
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)
}发布于 2017-04-18 06:24:35
举个例子,
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)发布于 2017-04-18 16:16:01
我要给你一个提示,告诉你该怎么做。基本上,你的问题是一个复杂的问题。如果运行循环,知道一个参数中的哪些值将与另一个参数的值交互,则会得到一个罚款for循环。
为了简单起见,我选择了2 arg。值从您的函数,因此将是2^3 (即,8)独特的情况。
因此,您的循环将如下所示(您可以实现"i“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)
}https://stackoverflow.com/questions/43464952
复制相似问题