开发者

if not conditions in R?

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

上一篇:

下一篇:

精彩评论

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

最新问答

问答排行榜