如何编写带4个参数的R语言ans函数?请求技术指导
Fixing Your R Function
ans() Hey there! Let's get your function working correctly—you're close, just a couple of syntax issues to sort out.
The Problems in Your Current Code
- You used
=for equality checks, but in R, we need==to test if two values are equal.=is for assigning values, which is why your code was throwing errors. - The
ifelse()function in R follows the structureifelse(condition, value_if_true, value_if_false)—you tried passing multiple conditions directly, which doesn't work. We need to nest a secondifelse()to handle the second condition.
Correct Versions of the Function
Option 1: Using Nested ifelse()
This works great if you need the function to handle vector inputs too:
ans <- function(a, b, x, y) { ifelse(a == 1 & b == 1, x, ifelse(a == 1 & b == 0, y, 0)) }
Option 2: Using Standard if-else Statements
If you're only working with single scalar values (not vectors), this version is more readable:
ans <- function(a, b, x, y) { if (a == 1 && b == 1) { return(x) } else if (a == 1 && b == 0) { return(y) } else { return(0) } }
Test It Out!
Let's verify the function behaves as expected:
ans(1, 1, "Hello", "World") # Returns "Hello" ans(1, 0, "Hello", "World") # Returns "World" ans(0, 1, "Hello", "World") # Returns 0 ans(2, 5, "Hello", "World") # Returns 0
内容的提问来源于stack exchange,提问作者hasan sohail
相关产品推荐
相关产品推荐

