【发布时间】:2018-04-30 18:32:44
【问题描述】:
我很难在用户定义的函数中设置正确的嵌套if statement。
我的样本数据是这样的
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 函数是什么?请参阅下面的 cmets。
所以预期的输出
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
【问题讨论】:
-
在 if 语句之后,您将返回 NA。您需要明确返回,例如
return("good")
标签: r if-statement dplyr