【发布时间】:2010-12-22 20:08:50
【问题描述】:
我正在编写的函数指定了物理开关的行为:如果一个值超过上限阈值,它应该打开,如果它低于下限阈值,它可以再次关闭。类似的逻辑将描述家用烤箱中的正常恒温器。显然我希望它在向量上起作用,这就是重点!
如果我有数据
S <- c(50, 100, 150, 180, 210, 200, 190, 182, 175, 185, 195, 205)
我的函数告诉烤箱温度是否正常。 “打开烤箱”的逻辑反义词。
R> thresholdOnOff(S, 180, 200)
[1] FALSE FALSE FALSE FALSE TRUE TRUE TRUE TRUE FALSE FALSE FALSE TRUE
问题是关于编程风格的:我首先尝试在其中使用“应用”函数编写它,但我忘记将环境考虑在内......所以我编写了一个带有“for”循环的工作版本 - 它我不喜欢,然后想起了环境,我不确定这两个版本:
thresholdOnOff <- local( {
## following the R inferno
f <- function(series, lower, upper, initialValue=FALSE) {
status <<- initialValue
switchOnOff <- function(x) {
if(x > upper)
status <<- TRUE
if(x < lower)
status <<- FALSE
return(status)
}
sapply(series, switchOnOff)
}
} )
thresholdOnOff <- function(series, lower, upper, initialValue=FALSE) {
## just guessing and reading from the documentation
status <- initialValue
switchOnOff <- function(x) {
if(x > upper)
assign('status', TRUE, inherits=TRUE)
if(x < lower)
assign('status', FALSE, inherits=TRUE)
return(status)
}
sapply(series, switchOnOff)
}
【问题讨论】:
标签: r