How logical negation operator “!” works

后端 未结 3 1195
孤独总比滥情好
孤独总比滥情好 2021-01-11 15:20

I am not trying to solve any particular problem, but trying to learn R and understand its logical negation operator \"!\" documented on page http://stat.ethz.ch/R-manual/R-d

3条回答
  •  囚心锁ツ
    2021-01-11 15:35

    First, I think the ! in != is not the ! operator. It is a distinct, != operator, which means "different from".

    Second, the ! operator is a logical one, the logical negation, and it must be applied to a logical vector :

    R> !(c(TRUE,FALSE))
    [1] FALSE  TRUE
    

    As numbers can be coerced to logical, it can also be applied to a numerical vector. In this case 0 will be considered as FALSE and any other value as TRUE :

    R> !c(1,0,-2.5)
    [1] FALSE  TRUE FALSE
    

    In your example, you are trying to apply this logical operator to a character string, which raises an error.

    If you want to subset lists, data frames or vectors by names, indices or conditions, you should read and learn about the indexing part of the R language, which is described in the R manuals and most of the introductory books and documents.

    One way to subset a list by names could be, for example :

    R> list[!(names(list) %in% "Forward")]
    $Backwards
    [1] 5 4 3 2 1
    

提交回复
热议问题