Skip to content

Exclusion of elements in a vector

4 messages · Stefan Fritsch, Chuck Cleland, Douglas Bates +1 more

#
Dear R Users,

I want to exclude elements in a vector by:

vector[-exclude]

is it intended to cause an error if no elements are excluded?
Error in -exclude 

or am I just definig exclude wrong, if no elements should be excluded?

with kind regards,

Stefan Fritsch
#
On 9/25/2008 7:43 AM, Stefan Fritsch wrote:
One approach would be to set "exclude" to a number greater than the
length of the vector:

x <- 1:10

exclude <- length(x) + 1

x[-exclude]
 [1]  1  2  3  4  5  6  7  8  9 10

library(fortunes)

fortune("dog")

Firstly, don't call your matrix 'matrix'. Would you call your dog 'dog'?
Anyway, it might clash with the function 'matrix'.
   -- Barry Rowlingson
      R-help (October 2004)

  
    
#
On Thu, Sep 25, 2008 at 8:15 AM, Chuck Cleland <ccleland at optonline.net> wrote:
Yes.  I'm not sure what you want to do can be done in a clean way.
The problem is with the semantics of the indexing operator for numeric
indices.  A "natural" way of expressing the empty numeric vector is

numeric(0)

When you use a numeric vector as a set of indices the first check is
to determine if all the values are negative, in which case the indices
are used to exclude rather than include.  However, you can't tell
whether the elements of the empty numeric vector are positive or
negative because there aren't any elements.  Thus

vector[numeric(0)]

is the same as

vector[-numeric(0)]
integer(0)
integer(0)

The error message you were getting results from the class of NULL,
which is different from the class of numeric(0).  Arithmetic
operations are defined, to some extent, for numeric(0) but not for
NULL.
#
Try this:

vector[ setdiff(seq_along(vector), as.numeric(idx)) ]

where idx is your vector of indices to exclude, e.g.
idx <- 3:4
idx <- numeric(0)
idx <- NULL

The last one gets converted to numeric(0) by
as.numeric so it still works.

On Thu, Sep 25, 2008 at 7:43 AM, Stefan Fritsch
<fritsch at bips.uni-bremen.de> wrote: