Hello,
I have two datasets 1 containing treatment/case data and the other containing potential controls. I need to match potential control to the cases but I need the output to look a certain way. I have used rangejoin and joinby but the output is not in the form I need. I have examples of the data and code and result as well as the desired result below.

TREATMENT DATASET EXAMPLE

Code:
* Example generated by -dataex-. To install: ssc install dataex
clear
input float(id case sex age)
1014 1 1  8
1017 1 1 10
1019 1 1  7
1019 1 1  9
1023 1 1  9
1025 1 0  6
1025 1 0  7
1025 1 1  7
1027 1 0  5
1027 1 1 10
1029 1 0  6
end
CONTROL DATASET EXAMPLE

Code:
* Example generated by -dataex-. To install: ssc install dataex
clear
input float(id control sex age)
1014 0 1  6
1017 0 0  7
1019 0 1  7
1023 0 0  6
1027 0 0  6
1027 0 0  7
1027 0 1  8
1027 0 1 10
1029 0 0 10
1031 0 0  6
1031 0 0 10
1032 0 0  7
1032 0 0 10
1032 0 1  6
1032 0 1  7
end
now I run rangejoin
Code:
rangejoin age -2 2 using"helptreat.dta", by(sex) suffix(_ctr)
and get:-

Code:
* Example generated by -dataex-. To install: ssc install dataex
clear
input float(id control sex age id_ctr case age_ctr)
1014 0 1 6 1019 1 7
1014 0 1 6 1025 1 7
1014 0 1 6 1014 1 8
1017 0 0 7 1027 1 5
1017 0 0 7 1025 1 6
1017 0 0 7 1029 1 6
1017 0 0 7 1025 1 7
1019 0 1 7 1019 1 7
1019 0 1 7 1025 1 7
1019 0 1 7 1014 1 8
1019 0 1 7 1019 1 9
1019 0 1 7 1023 1 9
end
What I need is a dataset that looks like
Code:
* Example generated by -dataex-. To install: ssc install dataex
clear
input float(id case_control sex age)
1014 0 0  4
1014 0 1  4
1014 0 1  6
1014 1 1  8
1017 0 0  1
1017 0 0  7
1017 1 1 10
1019 0 0  1
1019 0 1  7
1019 1 1  7
1019 1 1  9
end
So is there a way to transform the rangejoin dataset or should I be using a different command and if so what will yield the correct format output?
Thanks