# Matching a limited number of subjects from two populations based on age and sex using R

I have a dataset of 892 subjects 357 of whom had an operation and 535 who didn't. I'm planning on doing a follow up investigation of their current status but I can only do this for 300 of them in total. I know that age and sex influence this particular outcome and so want to limit the variation in these 2 variables between the two groups with which I follow up. What is the best way to select subjects from each group so as to minimize differences in age and sex? Is it safe to assume that it would be best to have 150 in each group? Here is an example of the data:

     subid operated   age   sex2
<dbl>   <fctr> <dbl> <fctr>
1      620      yes    42      1
2      621      yes    19      2
3      482       no    15      1
4      320       no    31      1
5      622      yes    32      1
6      623      yes    23      1
7      624      yes    22      1
8      285       no    15      2
9      625      yes    15      1
10     469       no    42      1


I previously used matchit to match all the subjects in the smaller population with an equal number in the larger population based on age and sex:

match.it <- matchit(group ~ age + sex2, data = mydataset, method="nearest", ratio=1)


However this does not solve my problem as it results in 357 subjects in each group and I can only invite 300 altogether.

• This really isn't a specific programming question. If you need advice for a proper statistical analysis, you should ask over at Cross Validated, not Stack Overflow. May 8 '17 at 19:00

my idea would be to sort by age and sub-sort by gender, then taking every other row for the two groups:

subjects.txt
1      620      yes    42      1
2      621      yes    19      2
3      482       no    15      1
4      320       no    31      1
5      622      yes    32      1
6      623      yes    23      1
7      624      yes    22      1
8      285       no    15      2
9      625      yes    15      1
10     469       no    42      1


group 1

cat subjects.txt | sort -k4n -k5n | awk 'NR%2==1{print $0}' 3 482 no 15 1 8 285 no 15 2 7 624 yes 22 1 4 320 no 31 1 10 469 no 42 1  group 2 cat subjects.txt | sort -k4n -k5n | awk 'NR%2==0{print$0}'
9      625      yes    15      1
2      621      yes    19      2
6      623      yes    23      1
5      622      yes    32      1
1      620      yes    42      1