Alex Alex - 3 months ago 8
R Question

Flexible filter for data frame in R

I need to filter one data frame using information from another. Names and number of columns could vary, as the number of conditions used for selection. For example the data frame that I would like to select from has the following structure:


name info_1 info_2 info_3 info_4 value
var1 aa 123 bb xx1 120
var2 bb 345 cc xx2 520
var3 aa 122 cc xx1 640
var4 dd 345 dd xx3 540
...


and data frame with information for filters:


info_1 info_3 info_4
aa bb xx1
bb cc N/A
dd N/A N/A
...


Number of columns in first data frame and number of columns that should be used for filters could be different for different data sets.
Is there is effective way to do such filtering? I think the filtering could be done in for loop for each column, however obviously it is not most efficient way to do.

Answer

You are certainly looking for:

df[Reduce('&', Map(function(u,v) v%in%u, filtering_df, df[names(filtering_df)])),]

#  name info_1 info_2 info_3 info_4 value
#1 var1     aa    123     bb    xx1   120
#3 var3     aa    122     cc    xx1   640
Comments