MATTHEW
MATTHEW

Reputation: 69

How to check if my table matches criteria in another table

I am quite new in R. This question seems to be quite common but I wasn't able to find a relevant answer from previous questions.

I have data as follow:

enter image description here

And have my maximum limitation as the following tables (each row is a separate criterion). enter image description here

And I would like to do a comparison of all the rows in my data matching those criteria and would like to have the yellow column as a return as a result.

enter image description here

Hope this is clear.

Upvotes: 0

Views: 285

Answers (1)

Sotos
Sotos

Reputation: 51592

We can use outer to get all combinations of values compared with the function greater than, (>). We do this for both columns and add them together. We are looking for both columns to exceed limit so basically looking for sum of 2. Once we have that, we can use rowSums to get the rows with at least 1 non-zero, i.e.

m1 <- (outer(df$column1, df1$Forcolumn1, `>`) + outer(df$column2, df1$Forcolumn2, `>`) == 2) * 1

#     [,1] [,2] [,3] [,4] [,5]
#[1,]    0    0    0    0    0
#[2,]    0    1    0    0    0
#[3,]    0    0    0    0    0
#[4,]    0    0    1    0    0
#[5,]    0    0    1    0    0
#[6,]    0    0    0    0    1

Using rowSums we get your expected output,

rowSums(m1 > 0)
#[1] 0 1 0 1 1 1

DATA

dput(df)
structure(list(Data = 1:6, column1 = 11:16, column2 = c(3, 3, 
2, 2, 1, 0)), class = "data.frame", row.names = c(NA, -6L))

dput(df1)
structure(list(max_limit = 1:5, Forcolumn1 = c(11, 11, 13, 14, 
15), Forcolumn2 = c(3, 2, 0, 1, -1)), class = "data.frame", row.names = c(NA, 
-5L))

Upvotes: 4

Related Questions