2

考虑这个实验:

Rgames> oof<-c(6,7,8,0,10)
Rgames> badoof<-vector()
Rgames> oof[badoof]
numeric(0)
Rgames> oof[-badoof]
numeric(0)
Rgames> oof[-0]
numeric(0)
Rgames> oof[-10]
[1]  6  7  8  0 10
Rgames> oof[-c(10,0)]
[1]  6  7  8  0 10

Rgames> oof[!(1:length(oof)%in% c(badoof) )]
[1]  6  7  8  0 10

我知道“只有负整数可以与零混合”是对子集的限制。我不清楚的部分是为什么两者都oof[badoof]没有oof[-badoof]返回。这里的背景是我有一个函数可以搜索坏数据并将它们从数据向量中删除。我希望不必badoof单独或通过 if/else 处理没有发现坏项目(即没有元素)的情况。上面最后一个例子,使用的例子%in%,但我想知道为什么R不接受索引“-badoof”结构。

编辑:鉴于 Hong Ooi 的回答,我也应该问:在内部使用负号[]是否真的是“NOT”操作,而不是改变指定索引的实际值?

4

1 回答 1

4

由于这个原因,它不起作用:

> x <- numeric(0)
> x
numeric(0)
> -x
numeric(0)
> identical(x, -x)
[1] TRUE

IOW,对没有元素的向量求反会使向量保持不变,因此使用向量的索引操作也将保持不变。

于 2013-07-05T15:58:15.903 回答