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"
set n(#) in a kdensity loop with different sample sizesHi Statalist, I am new here but this forum is been helpful several times. I am using stata15, and t…
How to prevent incorrect (Windows) file time attribute of graphic files produced with graph exportsaving a graph using graph export for the first time under a name such as graphtime.wmf saves the gr…
McDonald's omega for measurement modelWith a view to SEM, I want to evaluate a measurement model with six items (expressing behaviour freq…
Stacked chartsHi, I am trying to represent my data in a stacked chart. I have data on export and import. What I am…
How to interact a variable with Fixed Effect. Help!Hi! I am working on my final paper and could need som help. What i'm trying to do is to investigate …
Subscribe to:
Post Comments (Atom)
0 Response to Using _n to create a sequence variable using "if"
Post a Comment