【发布时间】:2017-08-28 18:10:11
【问题描述】:
假设我有以下创建的数据:
clear all
set obs 150
set seed 1234
foreach i in 1 2 {
gen year`i' = round(runiform()*4)
tostring year`i', replace
replace year`i' = "Super Low" if year`i'=="0"
replace year`i' = "Kinda Low" if year`i'=="1"
replace year`i' = "Average to Mediocre" if year`i'=="2"
replace year`i' = "Pretty High" if year`i'=="3"
replace year`i' = "Incredibly High" if year`i'=="4"
}
我最终想在 LaTeX 中创建一个表格,显示这两个变量的频率、百分比和百分比差异。重要的是,我想按第 1 年的频率对其进行排序。
发现它比我预期的更难,我想出了以下代码(感谢https://www.statalist.org/forums/forum/general-stata-discussion/general/1124796-any-way-to-save-row-percentages-output-as-a-matrix):
label define order 1 "Pretty High" 2 "Average to Mediocre" 3 "Kinda Low" 4 "Incredibly High" 5 "Super Low"
foreach i in 1 2 {
encode year`i', gen(y`i'_freq) label(order)
tab y`i'_freq, matcell(y`i'_freq)
mata: st_matrix("y`i'_pct", (st_matrix("y`i'_freq") :/ colsum(st_matrix("y`i'_freq"))))
}
matrix combined = y1_freq, y1_pct
foreach i in 2 {
matrix combined = combined, y`i'_freq, y`i'_pct
}
mata: st_matrix("c", (st_matrix("combined"), st_matrix("combined")[.,2] - st_matrix("combined")[.,4]))
matrix rownames c = "Pretty High" "Average to Mediocre" "Kinda Low" "Incredibly High" "Super Low"
matrix colnames c = "No. 1 Freq" "No. 1 Pct" "No. 2 Freq" "No. 2 Pct" "Difference"
esttab matrix(c), nomtitles
上面的问题是我硬编码了变量的排序。我如何将其概括为自动完成?
也感谢任何其他改进我的代码的提示。
【问题讨论】:
-
matrix combined = y1_freq, y1_pct, y2_freq, y2_pct将为您节省三行代码。