Reputation: 13
I'm looking into comparing a set of lists (containing only strings) and seeing if their contents exist in a main list called "universe". The problem is I don't know upfront how many lists I will be looking at, could be from one to 20 or more - these are created dynamically and this works OK. The single line of code below works fine but defeats my objective. To work with the code below then I'll have to create a switch with as many options as potential lists (group) which is messy.
allSE <- universe[group[[1]] & group[[2]] & group[[3]] ]
The two lines code below create an identical string to the commands in the square brackets above but simply doesn't work. It returns a single "NA" when I know there are 20 odd matches.
xnam <- paste0("group[[", 1:3,"]]")
allSE <- universe[paste(xnam, collapse= " & ")]
I've tried the formula command but that insists on a ~y since its for regression of course and not suitable - So how can I convince R it has commands between the square brackets and not a string for the command line in bold?
An example
universe <- c("ted","sara","fred","billy")
group1 <- as.logical(c("TRUE","TRUE","TRUE","TRUE"))
group2 <- as.logical(c("FALSE","TRUE","FALSE","TRUE"))
group3 <- as.logical(c("FALSE","TRUE","TRUE","TRUE"))
group <- list(group1, group2, group3)
universe[group[[1]] & group[[2]] & group[[3]]]
Expected results
should give sara and billy as these two appear in all three lists
Upvotes: 0
Views: 43
Reputation: 887611
We can use Reduce
with &
to compare the corresponding elements in the list
that are all TRUE
and it can be used to subset the 'universe'
universe[Reduce(`&`, group)]
#[1] "sara" "billy"
Or another option is to rbind
the list
elements and do a colSums
to check whether the number of TRUE elements are equal to the length
of list
universe[colSums(do.call(rbind, group))==length(group)]
Upvotes: 2