[R] Vector indices and minus sign

Gabor Grothendieck ggrothendieck at myway.com
Fri Nov 14 15:54:18 CET 2003

Just append the search string to the end of the target string,
i.e. x <- c(x,"x") so that it always matches something:

> my.list <- list(letters,LETTERS)
> lapply(my.list, function(x){x <- c(x,"x"); x[- grep("^x", x)]})
 [1] "a" "b" "c" "d" "e" "f" "g" "h" "i" "j" "k" "l" "m" "n" "o" "p" "q" "r" "s"
[20] "t" "u" "v" "w" "y" "z"

 [1] "A" "B" "C" "D" "E" "F" "G" "H" "I" "J" "K" "L" "M" "N" "O" "P" "Q" "R" "S"
[20] "T" "U" "V" "W" "X" "Y" "Z"

Date: Fri, 14 Nov 2003 13:16:24 +0000 
From: David Orme <d.orme at imperial.ac.uk>
To: <r-help at stat.math.ethz.ch> 
Subject: [R] Vector indices and minus sign 


I got caught out by this behaviour in 1.8.0 and I wondered why this 

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 
     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
index <- 5
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


More information about the R-help mailing list