說我有被創建的數據如下:如何排序矩陣標籤的結果
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'會爲您節省三行。 –