ifelse()函数
Usage
ifelse(test, yes, no)
- ifelse returns a value with the same shape as test which is filled with elements selected from either yes or no depending on whether the element of test is TRUE or FALSE.
- 如果test成立,执行yes,否则执行no,可以对数据做递归循环。
Example | 例子
> ??ifelse
> x <- c(1:10)
> # 单次判断函数
> ifelse(x<5,'T','F')
[1] "T" "T" "T" "T" "F" "F" "F" "F" "F" "F"
> # 函数嵌套应用
> ifelse(x<5,ifelse(x<3, 'A','B'), 'C')
[1] "A" "A" "B" "B" "C" "C" "C" "C" "C" "C"
先从整体判断x<5的真假:
1. 大于5的记作"C";
2. 小于5的再做判断;
小于3的记作"A";
大于3(且小于5)的记作"B"
两者区别
> a <- 0
> b <- c(1, 2, 3)
> ifelse(a==0, b, 0) #把判断正确的'b'返回到'a'中
[1] 1
> if(a==0){b}else{0}
[1] 1 2 3
> d <- c(1, 2, 3)
> e <- 0
> ifelse(d==c(1, 2, 3), 1, 0)
[1] 1 1 1
> if(d==c(1, 2, 3)){1}else{0}
[1] 1
Warning message:
In if (d == c(1, 2, 3)) { : 条件的长度大于一,因此只能用其第一元素
ifelse()与if(){}else(){}的区别:
ifelse()中的条件判断中可以得到多个逻辑结果,有多少个逻辑结果,ifelse()的返回值就有多少个元素,且不同的逻辑结果取不同的值。
if(){}else{}中的条件判断中只得到一个逻辑结果(如果有多个逻辑结果,会自动取第一个,并抛出警告)。然后根据这个逻辑结果,取后面表达式的值。
网友评论