Hi all,
I'm struggling with a formatting issue. I have a long list of variables and am calculating the median and interquartile range for each, and then want to display both values together in one cell with one digit to the right of the decimal for each number. I have set up a couple foreach loops to do this. Stata calculates the median and IQR in the first loop as expected. In the second loop, I have
foreach x in varlist {
tostring median_`x', replace
tostring iqr_`x', replace
gen `x'=median_`x' + " (" + iqr_`x' + ")"
}
No matter what numeric format I have going in to this second loop, the tostring command seems to get rid of the formatting I specified and makes the numbers formatted with as few digits as possible. For example, if I have median of 5.0 and IQR of 1.0 and want the output to look like "5.0 (1.0)", all I can get with tostring is "5(1)". I tried using format:
foreach x in varlist {
tostring median_`x', format (%3.1f) replace
tostring iqr_`x', format(%3.1f) replace
gen `x'=median_`x' + " (" + iqr_`x' + ')'
}
But I get the error "type mismatch" because I am trying to combine string and numeric subexpressions. Does anyone have any suggestions of how I can accomplish what I am trying to do? I've tried to search around for a way to do this by replacing a substring but I can't figure out how to do it when I am searching for the lack of something (i.e. a decimal point). Any help is much appreciated.
I'm struggling with a formatting issue. I have a long list of variables and am calculating the median and interquartile range for each, and then want to display both values together in one cell with one digit to the right of the decimal for each number. I have set up a couple foreach loops to do this. Stata calculates the median and IQR in the first loop as expected. In the second loop, I have
foreach x in varlist {
tostring median_`x', replace
tostring iqr_`x', replace
gen `x'=median_`x' + " (" + iqr_`x' + ")"
}
No matter what numeric format I have going in to this second loop, the tostring command seems to get rid of the formatting I specified and makes the numbers formatted with as few digits as possible. For example, if I have median of 5.0 and IQR of 1.0 and want the output to look like "5.0 (1.0)", all I can get with tostring is "5(1)". I tried using format:
foreach x in varlist {
tostring median_`x', format (%3.1f) replace
tostring iqr_`x', format(%3.1f) replace
gen `x'=median_`x' + " (" + iqr_`x' + ')'
}
But I get the error "type mismatch" because I am trying to combine string and numeric subexpressions. Does anyone have any suggestions of how I can accomplish what I am trying to do? I've tried to search around for a way to do this by replacing a substring but I can't figure out how to do it when I am searching for the lack of something (i.e. a decimal point). Any help is much appreciated.
Comment