Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

R removing items in a sublist from a list

Tags:

r

I have a list:

L <- c("a","b","c","d","e")

I also have a subset of this list:

L1 <- c("b","d","e")

I am trying to create a new list that does not contain the subset list.

I have tried:

L[L!%in%L1]
L[L%in%!L1]
L[L%in%-L1]

but this does not work. I would be grateful for your help.

like image 614
adam.888 Avatar asked Oct 26 '14 11:10

adam.888


2 Answers

It should be

L[!(L %in% L1)]

Because of operator precedence (?Syntax), you can also do

L[!L %in% L1]

Finally, you also have:

setdiff(L, L1)
like image 114
flodel Avatar answered Oct 15 '22 09:10

flodel


You could also play with vecsets:vsetdiff (disclaimer: I wrote this scary package). Unlike proper set theory as implemented in setdiff, vsetdiff will return all elements of a vector which do not appear in the second argument, thus allowing for multiple instances of a given value.

vsetdiff(L,L1)
[1] "a" "c"
vsetdiff(L1,L)
character(0)
like image 37
Carl Witthoft Avatar answered Oct 15 '22 08:10

Carl Witthoft