我遇到了一个简单的问题,但是没有写出代码。如果你能帮助我,我将不胜感激。
问题:创建一个将返回 2 个整数之和的函数。
我的代码:
q1 <- function(a, b) {
if (a == as.integer(a)) {
if (b == as.integer(b)) {
result1 <- a + b
}
}
} else {
result1 <- NA
result1
}
q1(3,6) - 假设它返回 9
q1(3.1,6) - 假设它返回 NA
顺便说一句,为什么我不能这样写语法?
if(is.integer(a) = TRUE){
最佳答案
这使用了 this answer 中的函数 (testInteger
) , 稍作编辑。它使用现在推荐的 isTRUE()
检查值是否为 TRUE
。
testInteger <- function(x){
test <- all.equal(x, as.integer(x), check.attributes = FALSE)
isTRUE(test)
}
q1 <- function(a, b) {
if (testInteger(a) && testInteger(b)) {
a + b
} else {
NA
}
}
q1(3, 6) # returns 9
q1(3.1, 6) # returns NA
关于r - 如何创建一个返回 2 个整数之和的函数?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/57229730/