I'm using Stata 16 on Windows. My data looks like (A):
id VisitDate MedClassId
33 2010 Corticost
33 2010 Antidepres
33 2012 Antidepres
33 2012 Vit D
33 2012 Corticost
33 2013 Vit D
33 2013 Corticost
33 2013 Antidepres
33 2015 Corticost
33 2015 Vit D
33 2015 Antidepres
where MedClassId is a numeric variable (displayed are labels).
The aim is to convert (A) to (B):
id VisitDate Antidepres Corticost Vit_D
33 2010 1 1 0
33 2012 1 1 1
33 2013 1 1 1
33 2015 1 1 1
After reshaping to wide, I had
id VisitDate Antidepres1 Corticost1 Vit_D1 Antidepres2 Corticost2 Vit_D2 Antidepres3 Corticost3
33 2010 0 1 0 1 0 0 . .
33 2012 1 0 0 0 0 1 0 1
33 2013 0 0 1 0 1 0 1 0
33 2015 0 1 0 0 0 1 1 0
As Antidepres1 Antidepres2 Antidepres3 are on different dates, I manually used
-egen Antidepres=rowmax(Antidepres*)- to get the information of Antidepres into a single variable, Antidepres.
Similarly for Corticost and Vit_D. That gave me form B.
There were thousands of ids and different ids had different drugs, how can we softcode (A) to (B)? Thank you for the help.
*---------------------------begin failed----------------------*
* I 1st added a prefix M_ to each variable of interest in the wide data. Then
preserve
keep M_*
ds
local varlist=r(varlist)
restore
foreach q in `varlist' {
di
local x=substr("`q'",1,strlen("`q'")-1)
cap confirm newvariable `x'
if _rc==0 {
gen `x'=rowmax(`x'*)
}
if _rc!=0 {
/* do nothing but move to the next `q' */
}
save test, replace
}
*----------------------end--------------------------*
id VisitDate MedClassId
33 2010 Corticost
33 2010 Antidepres
33 2012 Antidepres
33 2012 Vit D
33 2012 Corticost
33 2013 Vit D
33 2013 Corticost
33 2013 Antidepres
33 2015 Corticost
33 2015 Vit D
33 2015 Antidepres
where MedClassId is a numeric variable (displayed are labels).
The aim is to convert (A) to (B):
id VisitDate Antidepres Corticost Vit_D
33 2010 1 1 0
33 2012 1 1 1
33 2013 1 1 1
33 2015 1 1 1
After reshaping to wide, I had
id VisitDate Antidepres1 Corticost1 Vit_D1 Antidepres2 Corticost2 Vit_D2 Antidepres3 Corticost3
33 2010 0 1 0 1 0 0 . .
33 2012 1 0 0 0 0 1 0 1
33 2013 0 0 1 0 1 0 1 0
33 2015 0 1 0 0 0 1 1 0
As Antidepres1 Antidepres2 Antidepres3 are on different dates, I manually used
-egen Antidepres=rowmax(Antidepres*)- to get the information of Antidepres into a single variable, Antidepres.
Similarly for Corticost and Vit_D. That gave me form B.
There were thousands of ids and different ids had different drugs, how can we softcode (A) to (B)? Thank you for the help.
*---------------------------begin failed----------------------*
* I 1st added a prefix M_ to each variable of interest in the wide data. Then
preserve
keep M_*
ds
local varlist=r(varlist)
restore
foreach q in `varlist' {
di
local x=substr("`q'",1,strlen("`q'")-1)
cap confirm newvariable `x'
if _rc==0 {
gen `x'=rowmax(`x'*)
}
if _rc!=0 {
/* do nothing but move to the next `q' */
}
save test, replace
}
*----------------------end--------------------------*
Comment