开发者

if not conditions in R?

开发者 https://www.devze.com 2023-01-03 12:18 出处:网络
is there anything like \"if not\" conditions in R? easy Example (not working): fun <- function(x) { if (!x > 0) {print开发者_StackOverflow (\"not bigger than zero\")}

is there anything like "if not" conditions in R?

easy Example (not working):

fun <- function(x)
{
if (!x > 0) {print开发者_StackOverflow ("not bigger than zero")}
}

fun(5)


The problem is in how you are defining the condition. It should be

    if(!(x > 0)){ 

instead of

    if(!x > 0){ 

This is because !x converts the input (a numeric) to a logical - which will give TRUE for all values except zero. So:

> fun <- function(x){
+   if (!(x > 0)) {print ("not bigger than zero")}
+ }
> fun(1)
> fun(0)
[1] "not bigger than zero"
> fun(-1)
[1] "not bigger than zero"


Try:

if(!condition) { do something }


How about this?

fun <- function(x){
ifelse(x > 0, "not bigger than zero", "zero or less")
}
fun(5)
[1] "Bigger than zero"
0

精彩评论

暂无评论...
验证码 换一张
取 消