Filter multiple numeric columns basis another numeric vector using R

3188 views r

I have a large dataframe with 2 numeric columns (with repetition of numbers). I need to filter both the columns using the values in another numeric vector and create a new dataframe with matching entries in both columns.

Eg. Dataframe df has two columns A and B:

A . B
1 . 2
1 . 3
5 . 7
8 . 7
7 . 1

Then, I have a vector ind=c(1,2,5,7)

Desired output will be a new dataframe with only the following rows:

A . B
1 . 2
5 . 7
7 . 1

Note: Only keep those rows where values of both A and B matches the vector values.

answered question

1 Answer


df[df$A %in% ind & df$B %in% ind,]

This is a fairly basic subset - you only select those rows where both A and B are %in% your index vector ind.

posted this

Have an answer?


Please login first before posting an answer.