'How to subset rows from one dataframe based on matching values from a second smaller data frame in R

I want to select a control group from one data frame based of matching the age from a second data frame. As an example I have subject.df

subject.df
id age
1  1  55
2  2  62
3  3  73
4  4  54
5  5  66

I'd like to subset control.df based off of matching the age directly on a 1 to 1 matching from the subject.df dataframe.

control.df
id age
6   6  66
7   7  71
8   8  80
9   9  51
10 10  55
11 11  56
12 12  77
13 13  62
14 14  64
15 15  73
16 16  67
17 17  54
18 18  75
19 19  77
20 20  78
21 21  53
22 22  64
23 23  83
24 24  61
25 25  77

I'm fairly new to R. In the past I've used Matlab and in this instance would use a for loop to iterate over the control.df dataframe, but I've been told that R doesn't always like for loops and that it can be computationally difficult in R.

In the end I'll be doing this on a much larger data set where the subject group is around 250 and the control group is more than 40K so I know that 1:1 matching is possible.



Sources

This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.

Source: Stack Overflow

Solution Source