Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
743 views
in Technique[技术] by (71.8m points)

r - How logical negation operator "!" works

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-devel/library/base/html/Logic.html

It works for me when used in combination with =, in expressions such as:

1 != 2
TRUE

But I can't quite comprehend standalone application of this operator. For instance, can I use it to select elements of the list which do not have specific name. Here's my attempt to do that, but it did not work:

vector1 <- 1:5 # just making vector of 5 numbers
vector2 <- 5:1 # same vector backwards
list <- list(Forward=vector1, Backwards=vector2) # producing list with two elements
x = "Forward"
list[!x]

My output is:

Error in !x : invalid argument type

Will appreciate any hints on where my logic goes wrong in this case, and what are other good uses of this operator except for != case.

Thanks! Sergey

See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Answer

0 votes
by (71.8m points)

First, it's probably best not to think of != as ! acting on =, but rather as a separate binary operator altogether.

In general, ! should only be applied to boolean vectors. So this is probably more like what you are after:

vector1 <- 1:5 # just making vector of 5 numbers
vector2 <- 5:1 # same vector backwards
l <- list(Forward=vector1, Backwards=vector2) # producing list with two elements
x = "Forward"
l[!(names(l) %in% x)]

where names(l) %in% x returns a boolean vector along the names of the list l indicating whether they are contained in x or not. Finally, I avoided the use of list as a variable, since you can see it is a fairly common function as well.


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...