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

问题描述

我不是要解决任何特定问题,而是要尝试学习 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

在这种情况下我的逻辑出错的任何提示,以及除了 != case 之外该运算符还有哪些其他好的用途,我们将不胜感激.

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

where 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