Assigning Operators to R

I am trying to create a function in which users can select the operator that they want to use, which leads to a different result. But I can’t make it work. I know that we cannot assign operators to an R object and then use it as an operator based on the name of the R. object. Can I do this? Or maybe the best way to write a function?

test <- function(items, operator = "+"){
bank_alpha <- matrix(ncol=6)
colnames(bank_alpha) <- colnames(bank_alpha, do.NULL = FALSE, prefix = "Q")
colnames(bank_alpha)[6] <- "A"
alphabet <- LETTERS[seq(1:26)]

 for (i in 1:items) {
  item <- c(alphabet[i], alphabet[i operator 1], alphabet[i operator  2], alphabet[i operator  3], alphabet[i operator  4], alphabet[i operator 5])
  bank_alpha <- rbind(bank_alpha, item)
  bank_alpha <- na.omit(bank_alpha)
}
return(bank_alpha)
}

  test(items=4, operator = "-") 
+4
source share
3 answers

Check do.call, which takes a function name as an argument. Via

operator <- "+"
do.call(operator, list(2,3)

you will get 5as a result.

In your example:

test <- function(items, operator = "+"){
  bank_alpha <- matrix(ncol=6)
  colnames(bank_alpha) <- colnames(bank_alpha, do.NULL = FALSE, prefix = "Q")
  colnames(bank_alpha)[6] <- "A"
  alphabet <- LETTERS[seq(1:26)]

  for (i in 1:items) {
    item <- c(alphabet[i], alphabet[do.call(operator, list(i,1))], alphabet[do.call(operator, list(i,2))], alphabet[do.call(operator, list(i,3))], alphabet[do.call(operator, list(i,4))], alphabet[do.call(operator, list(i,5))])
    bank_alpha <- rbind(bank_alpha, item)
    bank_alpha <- na.omit(bank_alpha)
  }
  return(bank_alpha)
}

test(items=4, operator = "*") 

Beware, "-" in this case does not make sense.

+3
source

get() , :

> get('+')(5, 2)
[1] 7

get() , , .

(, 5 + 2).

+ :

> args('+')
function (e1, e2) 
NULL

, .

+2

R, %, infix . . .

test <- function(items, `%op%` = `+`){
    bank_alpha <- matrix(ncol=6)
    colnames(bank_alpha) <- colnames(bank_alpha, do.NULL = FALSE, prefix = "Q")
    colnames(bank_alpha)[6] <- "A"
    alphabet <- LETTERS[seq(1:26)]

    for (i in 1:items) {
       item <- c(alphabet[i], alphabet[i %op% 1], alphabet[i %op% 2], alphabet[i %op% 3], alphabet[i %op% 4], alphabet[i %op% 5])
       bank_alpha <- rbind(bank_alpha, item)
       bank_alpha <- na.omit(bank_alpha)
    }
    return(bank_alpha)
}

test(items=4, `%op%` = `*`)
+1

Source: https://habr.com/ru/post/1653577/


All Articles