如果参数negation为真,则condition应被否定。有更方便的方式来写这个吗?
foo <- function (x, type, negation){
if(type == 1){
condition <- x > 1
if(negation){
condition <- !condition
}
}
if(type == 2){
condition <- x == 5
if(negation){
condition <- !condition
}
}
x[condition]
}编辑:示例:
x <- 1:10
foo(x, 1, T) # 1
foo(x, 1, F) # 2 3 4 5 6 7 8 9 10
foo(x, 2, T) # 1 2 3 4 6 7 8 9 10
foo(x, 2, F) # 5发布于 2017-11-06 15:28:51
如果将来会有多种类型,请考虑使用S3 OOP系统。若否,则:
foo <- function(x, type, negation) {
condition <- switch(
type,
`1` = x > 1,
`2` = x == 5
)
x[xor(negation, condition)]
}发布于 2017-11-06 15:18:55
(在@PoGibas注释之后):
foo <- function (x, type, negation){
if(type == 1){
condition <- x > 1
}
if(type == 2){
condition <- x == 5
}
if(negation){
condition <- !condition
}
x[condition]
}还有其他改进的办法吗?
https://stackoverflow.com/questions/47139808
复制相似问题