R中比较运算符的功能 [英] Function for comparison operator in R

查看:54
本文介绍了R中比较运算符的功能的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我想定义一个R函数,在其中可以选择一个比较运算符,例如

I would like to define an R function in which I can select a comparison operator, like

fun <- function(x,y, op){
  if (op = "<"){
     comp_fun = <function for less than>
  } else if (op = "<="){
     comp_fun = <function for less equal than>
  }

return(comp_fun(x,y))
}

这只是一个玩具示例,但我想知道哪个函数实现了四个<",< =",>"和> ="运算符.

This is just a toy example, but I would like to know which function implement the four "<", "<=", ">" and ">=" operators.

推荐答案

运算符已经是函数,因此您不需要额外的层.

Operators are functions already, so you don't need an extra layer.

x <- 1:5
y <- 5:1
`<`(x, y)
## [1]  TRUE  TRUE FALSE FALSE FALSE
"<"(x, y)
## [1]  TRUE  TRUE FALSE FALSE FALSE

尽管如James和Roland所述,您可以使用 get match.fun .

Though as James and Roland mentioned, you can use get or match.fun.

op <- "<"
get(op)(x, y)
## [1]  TRUE  TRUE FALSE FALSE FALSE
match.fun(op)(x, y)
## [1]  TRUE  TRUE FALSE FALSE FALSE

请注意,直接使用 op 变量不起作用

Though be warned that using the op variable directly doesn't work

op(x, y)
## Error: could not find function "op"

这篇关于R中比较运算符的功能的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆