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 = "-")
Assignment Operator In R, the main and most used by R users is left-arrow operator ( <- ). The obj <- expr means “assign the value of the result from the operation on the right hand side ( expr ) to the object on the left hand side ( obj )”.
You can map operator symbols to those functions to retrieve the proper function, then assign it to your op variable and compute op(a, b). Show activity on this post. It should be expression = a + c + b .
In the R Commander, you can click the Data set button to select a data set, and then click the Edit data set button. For more advanced data manipulation in R Commander, explore the Data menu, particularly the Data / Active data set and Data / Manage variables in active data set menus.
You can use the get()
functionally to dynamically call the operator functions, e.g.:
> get('+')(5, 2)
[1] 7
The get()
function takes a string as input and returns a reference to the function corresponding to that string, if it exists.
Usually operators are called with one function argument on the left and one on the right (e.g. 5 + 2
).
The +
operator function itself however just takes two arguments as input:
> args('+')
function (e1, e2)
NULL
This is why we can call it as we did above.
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.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With