Hi
I have a dataset consisting of dispensed medication items - there are multiple records for each individual, as they've had multiple items dispensed. These medications fall into one of two groups - OST or AP. For each group of medications, I want to label each record with a number indicating its place in the sequence of dispensed medication items for that individual.
However, when I try to use _n for this purpose, I can't seem to specify which type of medication to count - the sequences I generate seem to count all items, not just the one I'm interested in. Here is an example of my code:
sort id ddate
gen ost_seq=_n if ost_item==1
gen ap_seq= _n if ap_item==1
(id is my individual identifer for each person
ddate is the dispensing date
ost_seq is the new variable I am trying to create which indicates the sequence of OST items per individual - same for the AP variable
ost_item and ap_item is a 0/1 variable indicating which group of medications the item belongs to (the groups are mutually exclusive)
But when I then inspect my data, the items are numbered as if the "if" condition wasn't there e.g.
id ost_item ap_item ost_seq
1 1 0 1
1 0 1 2
1 1 0 3
2 0 1 1
2 0 1 2
3 1 0 3
Instead what I'd like it to look like is
id ost_item ap_item ost_seq
1 1 0 1
1 0 1 .
1 1 0 2
2 0 1 .
2 0 1 .
3 1 0 1
(and same for ap_seq, though haven't included here just for clarity)
I can't seem to find any guidance about using group identifiers/sequences like this with an "if" condition so would welcome advice.
Many thanks
Related Posts with Using _n to create a sequence variable using "if"
How to calculate Sigma (standard deviation of weekly stock return)Hello all Statalist members. I would like to calculate SIGMA (denotes standard deviation of weekly s…
Converting Date-Month-Year (string) to yearDear Stata Members I have an issue which I know is the most answered questions in this form, I tried…
Categorical Variables Hi, I'm an ultra-beginner to Stata and everything related to it. Nevertheless, I have to fix this …
Ho, ho, ho! Wild bootstrap tests for everyone!I've translated the guts of my boottest program from Mata to Julia, producing the Julia package Wild…
Showing a different mean in tabstat I tabulated in my data type of error cases by the number of children. After using sum and N along w…
Subscribe to:
Post Comments (Atom)
0 Response to Using _n to create a sequence variable using "if"
Post a Comment