根据命令存储和使用运算符

Store and use operators on command

我如何(并且可以)在 if 和 else 函数中对命令使用不同的运算符?

x <- as.numeric(c(1,1,4,5,6,7,8))

if(mean(x) < 3){operator.is <- <}else{operator.is <- >}

sub <- subset(x, x operator.is 2)

#expected results
sub
[1] 3 4 5 6 7 8

我想根据 if 语句将运算符存储在 "operator.is" 中。然而,我似乎无法存储运算符并在子集函数中使用它。后来在想用这个运算符来做子集。如果没有这个,我将需要复制并粘贴整个代码才能使用其他运算符。有什么优雅简单的方法可以解决这个问题吗?

提前致谢

运算符可以用 % 符号赋值:

`%op%` = `>`

vector <- c(1:10)

vector2 <- subset(vector, vector %op% 5)

你的情况:

x <- as.numeric(c(1,1,4,5,6,7,8))

if(mean(x) < 3){`%operator.is%` <- `<`}else{`%operator.is%` <- `>`}

sub <- subset(x, x %operator.is% 2)
x <- as.numeric(c(1,1,4,5,6,7,8))

if(mean(x) < 3){`%my_op%` <- `<`}else{`%my_op%` <- `>`}

sub <- subset(x, x %my_op% 2)
sub
##[1] 4 5 6 7 8

"Things to remember while defining your own infix operators are that they must start and end with %. Surround it with back tick (`) in the function definition and escape any special symbols."

来自 https://www.datamentor.io/r-programming/infix-operator/

最好跟随@Oliver 的脚步

x <- as.numeric(c(1,1,4,5,6,7,8))

if(mean(x) < 3){operator.is <- `<`}else{operator.is <- `>`}

sub <- subset(x, operator.is(x,2))
sub
##[1] 4 5 6 7 8