正确设置多个if语句 [英] Setting multiple if statements correctly
问题描述
我很难在用户定义的函数中设置适当的嵌套 if语句
。
I have difficulty to set proper nested if statement
in a user-defined function.
我的示例数据就像这样
test <- data.frame(x=rev(0:10),y=10:20)
if_state <- function(x,y) {
if (x==min(x) && y==max(y)) {
"good"
} else if (max(x)/2==y[which(y==15)]/3) { # to find when x=5 and y=5 condition if it is true set class to "y==5"
"y==5"
}
NA
}
> test
x y
1 10 10
2 9 11
3 8 12
4 7 13
5 6 14
6 5 15
7 4 16
8 3 17
9 2 18
10 1 19
11 0 20
library(dplyr)
test %>%
mutate(class = if_state(x,y))
x y class
1 10 10 NA
2 9 11 NA
3 8 12 NA
4 7 13 NA
5 6 14 NA
6 5 15 NA
7 4 16 NA
8 3 17 NA
9 2 18 NA
10 1 19 NA
11 0 20 NA
我不知道为什么if语句不能正常工作?
问题是与dplyr的 case_when
相同的基本R函数是什么?请参阅下面的注释。
I don't know why the if statement is not working correctly?
The question is what is the base R function that work same as dplyr's case_when
? please see the comments below.
因此预期输出
x y class
1 10 10 NA
2 9 11 NA
3 8 12 NA
4 7 13 NA
5 6 14 NA
6 5 15 y==5
7 4 16 NA
8 3 17 NA
9 2 18 NA
10 1 19 NA
11 0 20 good
推荐答案
R函数返回在调用期间评估的最后一个值,即使没有显式调用返回
(请参见此答案以了解更多信息);因此,其中 NA
是 if_state
函数中最后求值的值(因为它位于之外) if-else if
控制流,因此将始终对其进行评估),即使,它也会始终返回
和 NA
if else如果
条件为真。为了使功能按预期工作,您需要将 NA
移至else语句:
R functions return the last value evaluated evaluated during their invocation, even without an explicit call to return
(see this answer for more detail); so, where NA
is the last value evaluated in your if_state
function (as it's outside the if-else if
control flow, and so will always be evaluated), it will always return NA
, even when the if
and else if
conditions are true. For your function to work as you expect, you need to move NA
into an else statement:
if_state <- function(x,y) {
if (x == min(x) && y == max(y)) {
"good"
} else if (max(x)/2 == y[which(y == 15)]/3) {
"y==5"
} else {
NA
}
}
请注意,使用dplyr时,请测试多个确定返回值的条件通常使用 case_when
可以更简洁地完成:
Note that when using dplyr, testing for multiple conditions to determine a return value is often more succinctly accomplished with case_when
:
test %>% mutate(class = case_when(
x == min(x) && y == max(y) ~ "good",
max(x)/2 == y[which(y == 15)]/3 ~ "y == 5",
TRUE ~ NA_character_
))
编辑:基于OP的说明和eipi10的帮助,这是最终功能:
based on OP's clarification and eipi10's help, here is the final function:
if_state = function(x, y) {
case_when(x == min(x) && y == max(y) ~ "good",
x == max(x)/2 & y/3 == 5 ~ "y==5",
TRUE ~ NA_character_)
}
这篇关于正确设置多个if语句的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!