Sam Sam - 3 months ago 11
R Question

Assigning operators into an R variable

I am trying to create a function where users can select the operator they want to use, which result in a different output. But I can't seem to get it to work. I know that we can't assign operators into an R object and then use it as an operator based on the R object name. Is there a way I could do this? Or perhaps a better way to write the 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 = "-")

Answer

Check out do.call, which takes the name of a function as an argument. With

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

you will get 5 as the 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, "-" doesn't make sense in this case.