本文介绍了逻辑否定运算符如何“!"作品的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我不是要解决任何特定问题,而是要学习R并理解其逻辑否定运算符!".记录在页面 http://stat.ethz中.ch/R-manual/R-devel/library/base/html/Logic.html

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]

我的输出是:

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.

谢谢!谢尔盖

推荐答案

首先,最好不要将!= 视为 =起作用,而是完全作为一个单独的二进制运算符.

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)]

其中 names(l)%in%x 返回沿列表 l 的名称的布尔矢量,指示它们是否包含在 x 还是不.最后,我避免使用 list 作为变量,因为您可以看到它也是一个相当常见的函数.

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.

这篇关于逻辑否定运算符如何“!"作品的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!

08-16 00:49