[R] Vector indices and minus sign
Peter Dalgaard
p.dalgaard at biostat.ku.dk
Fri Nov 14 14:53:57 CET 2003
David Orme <d.orme at imperial.ac.uk> writes:
> Hi,
>
> I got caught out by this behaviour in 1.8.0 and I wondered why this
> happens:
>
> I have a list of vectors and was using lapply and grep to remove
> matched elements that occur in only a subset of the elements of the
> list:
> locs <- lapply(locs, function(x){x[- grep("^x", x)]})
>
> The problem is that where the grep finds no matches and hence returns
> a vector of length 0, all the elements of x were removed, rather than
> none. As a toy example:
>
> vect <- 1:10
> vect[-5]
> index <- 5
> vect[-index]
> index <- numeric()
> vect[-index] # I was expecting this to give all the elements of vect
> rather than an empty vector
> vect[index] # does the same thing
...which is the point: -index is just as empty as index and indexing
by an empty vector gives you nothing. Probably the most convenient way
out is
ix <- 1:10
found <- numeric()
vect(!(ix %in% found))
or maybe (I suspect more efficient)
sel <- rep(T,10)
found <- numeric()
sel[found] <- FALSE
x[sel]
--
O__ ---- Peter Dalgaard Blegdamsvej 3
c/ /'_ --- Dept. of Biostatistics 2200 Cph. N
(*) \(*) -- University of Copenhagen Denmark Ph: (+45) 35327918
~~~~~~~~~~ - (p.dalgaard at biostat.ku.dk) FAX: (+45) 35327907
More information about the R-help
mailing list