[R] Removing multiple elements from a vector or list

arun smartpink111 at yahoo.com
Mon Apr 15 23:30:57 CEST 2013


Hi,
 vec1<- letters
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.

>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")] 
>
>this does not work 
>
>Thanks, 
>Johnny



More information about the R-help mailing list