[R] Removing multiple elements from a vector or list

David Winsemius dwinsemius at comcast.net
Tue Apr 16 00:31:14 CEST 2013

On Apr 15, 2013, at 2:30 PM, arun wrote:

> Hi,
>  vec1<- letters

alp <- as.list(letters) would have constructed the vector that was described.

> vec1[!grepl("b|r|x",alp)]
> # [1] "a" "c" "d" "e" "f" "g" "h" "i" "j" "k" "l" "m" "n" "o" "p" "q" "s" "t" "u"
> #[20] "v" "w" "y" "z"
>  vec1[!vec1%in% c("b","r","x") ]
> # [1] "a" "c" "d" "e" "f" "g" "h" "i" "j" "k" "l" "m" "n" "o" "p" "q" "s" "t" "u"
> #[20] "v" "w" "y" "z"
> alp<-lapply(seq_along(vec1),function(i) vec1[i])
>  res<-alp[!grepl("b|r|x",alp)]
> unlist(res)
> # [1] "a" "c" "d" "e" "f" "g" "h" "i" "j" "k" "l" "m" "n" "o" "p" "q" "s" "t" "u"
> #[20] "v" "w" "y" "z"
> unlist(alp[!alp%in%c("b","r","x")])
>  #[1] "a" "c" "d" "e" "f" "g" "h" "i" "j" "k" "l" "m" "n" "o" "p" "q" "s" "t" "u"
> #[20] "v" "w" "y" "z"
> A.K.

All good. There would be an additional way to do this if the list were first assigned names. (At the moment the list only has positions for reference.)

alp <- setNames(alp, letters[1:26])
# Something like that initial code would succeed:

alp <- alp[ !names(alp) %in% c("b","r","x")]

The result is still a list.

>> If I for example have a list (or vector)  that contains all the letters in the alphabet. 
>> alp <- list("a","b","c",......................."z")  this is of course not the exact code 
>> How can I remove multiple elements at one time without knowing their location in the list. Say I want to remove b,r,x? 
>> Same question if apl is a vector 
>> I have tried 
>> alp <- alp[-c("b","r","x")] 

You _cannot_use_negative_indexing_with_names (or values). You could have used logical indexing:

alp [ sapply(alp, function(x) !x %in% c("b","r","x") ) ]

# OR perhaps the most compact solution offered so far;  numeric indexing with the minus unary operator:

alp[ -grep("b|r|x", alp) ]


David Winsemius
Alameda, CA, USA

More information about the R-help mailing list