Hello I am attempting to create a metadata data file that includes a column that lists out all the value codes + label for each variable.
I am a SAS user primarily and haven't used looping in STATA in quite a while. I have been able to loop over the variables but can't remember how to save the results in a matrix that I can get into a dataset.
I want to end up with this:
Here are the steps that I have gone through so far:
1. After loading data, 'uselabel' to create a dataset with all the format information.
2. read through this post: https://www.stata.com/meeting/oceani...a17_Vidmar.pdf and ran the following code
gen recnum=_n
levelsof lname, local(levels)
foreach x of local levels {
local fullab
qui su recnum if lname=="`x'"
local j=r(min)
local k=r(max)
forval i=`j'/`k' {
local val=value[`i']
local lab=label[`i']
local fullab `fullab' `val', `lab' |
}
local lenlab=strlen("`fullab'")-2
local fullab=substr("`fullab'",1,`lenlab')
}
3. looked at the contents of the fullab macro variable
di "`fullab'"
-5, -5: Don't know | -3, -3: Missing | 1, 1: Often | 2, 2: Sometimes | 3, 3: Never
4. Looks like it iterated and contains something close enough to what I need. How do I capture the information from each loop in a matrix and save it to a dataset?
Thanks for any help!
I am a SAS user primarily and haven't used looping in STATA in quite a while. I have been able to loop over the variables but can't remember how to save the results in a matrix that I can get into a dataset.
I want to end up with this:
lname | values |
var1 | -5: Don't know, -3 Missing, 1: Yes, 2: No |
var2 | -5: Don't know, -3 Missing, 1: Often, 2: Sometimes, 3: Never |
1. After loading data, 'uselabel' to create a dataset with all the format information.
lname | value | label |
var1 | -5 | -5: Don't know |
var1 | -3 | -3: Missing |
var1 | 1 | 1: Yes |
var1 | 2 | 2: No |
var2 | -5 | -5: Don't know |
var2 | -3 | -3: Missing |
var2 | 1 | 1: Often |
var2 | 2 | 2: Sometimes |
var2 | 3 | 3: Never |
gen recnum=_n
levelsof lname, local(levels)
foreach x of local levels {
local fullab
qui su recnum if lname=="`x'"
local j=r(min)
local k=r(max)
forval i=`j'/`k' {
local val=value[`i']
local lab=label[`i']
local fullab `fullab' `val', `lab' |
}
local lenlab=strlen("`fullab'")-2
local fullab=substr("`fullab'",1,`lenlab')
}
3. looked at the contents of the fullab macro variable
di "`fullab'"
-5, -5: Don't know | -3, -3: Missing | 1, 1: Often | 2, 2: Sometimes | 3, 3: Never
4. Looks like it iterated and contains something close enough to what I need. How do I capture the information from each loop in a matrix and save it to a dataset?
Thanks for any help!
Comment