将运算符分配给R变量 [英] Assigning operators into an R variable
本文介绍了将运算符分配给R变量的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
我正在尝试创建一个函数,用户可以选择想要使用的运算符,从而产生不同的输出.但是我似乎无法使其正常工作.我知道我们不能将运算符分配到R对象中,然后根据R对象名称将其用作运算符.有办法吗?还是编写函数的更好方法?
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 = "-")
推荐答案
签出do.call,它将函数名作为参数.使用
Check out do.call, which takes the name of a function as an argument. With
operator <- "+"
do.call(operator, list(2,3)
您将得到 5
作为结果.
在您的示例中:
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.
这篇关于将运算符分配给R变量的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!
查看全文