
Nội dung
Giới thiệu gói lệnh gtools
Để tăng tốc tính toán cho các câu lệnh truyền thống ở Stata như collapse, egen, xtile, isid, levelsof, contract, distinct… bạn có thể sử dụng các lệnh tương ứng từ gói gtools
. Đầu tiên, bạn cần tải gói lệnh này về máy bằng lệnh ssc install gtools, replace
hoặc cập nhật phiên bản mới của gói lệnh bằng gtools, update
.
Sau đây là một số câu lệnh trong gói gtools
Gtools | Thông thường | Công dụng |
---|---|---|
gcollapse | collapse | Efficiently make dataset of summary statistics. |
gcontract | contract | Efficiently make dataset of frequencies and percentages. |
gquantiles | pctile, xtile, and _pctile | Efficiently compute percentiles (quantiles), categories, and frequencies. |
gegen | egen | Efficient implementation of by-able egen functions. |
gisid | isid | Efficiently check for unique identifiers |
gduplicates | duplicates | Efficiently report, tag, or drop duplicate observations. |
glevelsof | levelsof | Efficiently get levels of variable. Unlike levelsof, it can take a single variable or multiple variables. |
gtoplevelsof | contract | Quickly tabulate most common levels of variable list. |
gunique | unique | Efficiently calculate unique values of a variable or group of variables. |
gdistinct | distinct | Efficiently report number(s) of distinct observations or values. |
greshape | reshape | converts data from wide to long form and vice versa |
gstats | summarize, tabstat | Various statistical fucntions and transformations. |
hashsort | sort | hashsort hashes the data and sorts the hash, and then it sorts one observation per group. |
Ví dụ thực hành
Sử dụng bộ dữ liệu auto.dta
sẵn có trên máy tính, phần bên dưới sẽ minh họa cách sử dụng các lệnh trong gói gtools

gcollapse
Biến đổi tập dữ liệu trong bộ nhớ sang một tập dữ liệu mới gồm các giá trị trung bình, tổng, trung vị,… Câu lệnh chỉ áp dụng cho các biến dạng số.
gcollapse (stat) out = src [(stat) out = src …] [if] [if] [weight], by(varlist) [options]
. sysuse auto, clear (1978 automobile data) . gen h1 = headroom . gen h2 = headroom . local lbl labelformat(#stat:pretty# #sourcelabel#) . gcollapse (mean) mean = price (median) p50 = gear_ratio, by(make) merge v Radix sort on 64-bit hash (16-bits at a time) N = 74; 74 balanced groups of size 1 There were no hash collisions: 1 variables, 74 obs, 74 groups . disp "`:var label mean', `:var label p50'" (mean) Price, (median) Gear ratio . gcollapse (iqr) irq? = h? (nunique) turn (p97.5) mpg, by(foreign rep78) bench(2) wild Parsed by variables, sources, and targets; .004 seconds Recast source variables to save memory; .002 seconds Dropped superfluous variables; .001 seconds Generated additional targets; 0 seconds Parsed by variables; .003 seconds Plugin step 1: Read in by variables (0.000 seconds). Plugin step 2: Hashed by variables (0.000 seconds). Plugin step 3: Set up panel (0.000 seconds). Plugin step 4: Created indexed array with sorted by vars (0.000 seconds). Plugin step 5: Generated output array (0.000 seconds). Plugin step 6: Copied collapsed data to stata (0.000 seconds). C plugin runtime; 0 seconds Internal gtools runtime (internals); .003 seconds Program exit executed; 0 seconds
gcontract
Thay thế tập dữ liệu trong bộ nhớ bằng một tập dữ liệu mới bao gồm tất cả các kết hợp của biến trong danh sách và một biến mới chứa tần suất của mỗi kết hợp tổ hợp. Người dùng có thể tùy chọn yêu cầu tỷ lệ phần trăm và số lượng và tỷ lệ tích lũy.
gcontract varlist [if] [if] [fweight], [options]
. sysuse auto, clear (1978 automobile data) . gcontract foreign [fw = turn], freq(f) percent(p)
gquantiles
Lệnh gquantiles
cung cấp một số tùy chọn bổ sung cho ba lệnh Stata được tích hợp sẵn: pctile
, xtile
, và _pctile
gquantiles [newvarname =] exp [if] [in] [weight], {_pctile|xtile|pctile} [options]
. sysuse auto, clear (1978 automobile data) . gquantiles 2*price, _pctile nq(10) . gquantiles p10 = 2*price, pctile nq(10) . gquantiles x10 = 2*price, xtile nq(10) by(rep78) . fasterxtile xx = log(price) [w = weight], cutpoints(p10) by(foreign) (analytic weights assumed)
gegen
gegen target = stat(source) [if] [in] [weight], by(varlist)
. sysuse auto, clear (1978 automobile data) . gegen tag = tag(foreign) . gegen group = tag(-price make) '-' interpreted as negative; use option -ds- to interpret as varlist (to suppress this warning, use option -nods-) . gegen p2_5 = pctile(price) [w = weight], by(foreign) p(2.5) (analytic weights assumed)
gisid
gisid varlist [if] [in], [options]
. sysuse auto, clear (1978 automobile data) . gisid make, missok . gisid price in 1 / 2
gduplicates
gduplicates varlist [if] [in], [options gtools(gtools_options)]
. sysuse auto, clear (1978 automobile data) . gduplicates report foreign Duplicates in terms of foreign ──────────┬─────────────────────────── copies │ observations surplus ──────────┼─────────────────────────── 22 │ 22 21 52 │ 52 51 ──────────┴─────────────────────────── . gduplicates report rep78 if foreign, gtools(bench(3)) Duplicates in terms of rep78 Plugin setup; 0 seconds Generated targets; .001 seconds Parsed by variables; .001 seconds Plugin step 1: Read in by variables (0.000 seconds). Plugin step 2.1: Determined hashing strategy (0.000 seconds). Plugin step 2.3: Bijected integers to natural numbers (0.000 seconds). Plugin step 2.4: Sorted integer-only hash (0.000 seconds). Plugin step 2: Hashed by variables (0.000 seconds). Plugin step 3.1: Created group index (0.000 seconds). Plugin step 3.2: Normalized group index and Stata index (0.000 seconds). Plugin step 3: Set up panel (0.000 seconds). Plugin step 4: Created indexed array with sorted by vars (0.000 seconds). Plugin step 5: Copied back encoding to Stata (0.000 seconds). C plugin runtime; 0 seconds Internal gtools runtime; .002 seconds Plugin setup; 0 seconds Generated targets; .001 seconds Parsed by variables; .001 seconds Plugin step 1: Read in by variables (0.000 seconds). Plugin step 2.1: Determined hashing strategy (0.000 seconds). Plugin step 2.3: Bijected integers to natural numbers (0.000 seconds). Plugin step 2.4: Sorted integer-only hash (0.001 seconds). Plugin step 2: Hashed by variables (0.001 seconds). Plugin step 3.1: Created group index (0.000 seconds). Plugin step 3.2: Normalized group index and Stata index (0.000 seconds). Plugin step 3: Set up panel (0.000 seconds). Plugin step 4: Created indexed array with sorted by vars (0.000 seconds). Plugin step 5: Copied back encoding to Stata (0.000 seconds). C plugin runtime; 0 seconds Internal gtools runtime; .003 seconds (52 missing values generated) ──────────┬─────────────────────────── copies │ observations surplus ──────────┼─────────────────────────── 1 │ 1 0 3 │ 3 2 9 │ 18 16 ──────────┴───────────────────────────
glevelsof
Efficiently get levels of variable. Unlike levelsof, it can take a single variable or multiple variables.
glevelsof varlist [if] [in], [options]
. sysuse auto, clear (1978 automobile data) . glevelsof rep78, local(levels) sep(" | ") 1 | 2 | 3 | 4 | 5 . glevelsof foreign mpg if price < 4000, loc(lvl) sep(" | ") colsep(", ") `"0, 19"' | `"0, 20"' | `"0, 22"' | `"0, 24"' | `"0, 29"' | `"0, 30"' | `"1, 26"' | `"1, 30"' | `"1, 31"' | `"1, 35"' . glevelsof foreign mpg in 10 / 70, gen(uniq_) nolocal
gtop
gtop varlist [if] [in] [weight], [options]
. sysuse auto, clear (1978 automobile data) . gtoplevelsof foreign rep78 foreign rep78 | N Cum Pct (%) Cum Pct (%) ────────────────────────────────────────────────────── Domestic 3 | 27 27 36.5 36.5 Domestic 4 | 9 36 12.2 48.6 Foreign 4 | 9 45 12.2 60.8 Foreign 5 | 9 54 12.2 73.0 Domestic 2 | 8 62 10.8 83.8 Domestic . | 4 66 5.4 89.2 Foreign 3 | 3 69 4.1 93.2 Domestic 1 | 2 71 2.7 95.9 Domestic 5 | 2 73 2.7 98.6 Foreign . | 1 74 1.4 100.0 . gtop foreign rep78 [w = weight], ntop(5) missrow groupmiss pctfmt(%6.4g) colmax(3) (analytic weights assumed) foreign rep78 | W Cum Pct (%) Cum Pct (%) ──────────────────────────────────────────────────────────── Dom... 3 | 92,940 92,940 41.6 41.6 Dom... 4 | 31,790 124,730 14.23 55.82 Dom... 2 | 26,830 151,560 12.01 67.83 For... 5 | 21,630 173,190 9.68 77.51 For... 4 | 19,870 193,060 8.893 86.4 ──────────────────────────────────────────────────────────── Missing (any) | 14,230 207,290 6.369 92.77 Other | 16,150 223,440 7.228 100
greshape
greshape subcommand list, i(i) j(j) [options]
greshape wide varlist, i(i) j(j) [options] greshape long prefixlist, i(i) [j(j) string options]
greshape spread varlist, j(j) [options] greshape gather varlist, j(j) value(value) [options]
. sysuse auto, clear (1978 automobile data) . keep price foreign . gen j = _n . greshape wide price, i(foreign) j(j) (note: j = 1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 > 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74) Data long -> wide ───────────────────────────────────────────────────────────────────────────── Number of obs. 74 -> 2 Number of variables 3 -> 75 j (74 values) j -> (dropped) xij variables: price -> price1 price2 ... price74 ───────────────────────────────────────────────────────────────────────────── . greshape long price, i(foreign) j(j) (note: j = 1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 > 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74) Data wide -> long ───────────────────────────────────────────────────────────────────────────── Number of obs. 2 -> 148 Number of variables 75 -> 3 j (74 values) -> j xij variables: price1 price2 ... price74 -> price ─────────────────────────────────────────────────────────────────────────────
gstats
gstats {sum|tab} varlist [if] [in] [weight], [by(varlist) options]
. sysuse auto, clear (1978 automobile data) . gstats sum price [pw = gear_ratio / 4] Price ───────────────────────────────────────────────────────────── Percentiles Smallest (weighted) 1% 3291 3291 5% 3748 3667 10% 3895 3798 Obs 55.775 25% 4187 3799 Sum of Wgt. 55.775 50% 4934 Mean 6027.133 Largest Std. Dev. 2799.391 (weighted) 75% 6303 11497 90% 10372 12990 Variance 7836589 95% 12990 13466 Skewness 1.741214 99% 15906 15906 Kurtosis 5.263277 . gstats tab price mpg, by(foreign) matasave foreign variable | n sum mean min max sd ────────────────────────────────────────────────────────────────────────────────── Domestic price | 52 315766 6072.423 3291 15906 3097.104 mpg | 52 1031 19.82692 12 34 4.743297 ────────────────────────────────────────────────────────────────────────────────── Foreign price | 22 140463 6384.682 3748 12990 2621.915 mpg | 22 545 24.77273 14 41 6.611187 ────────────────────────────────────────────────────────────────────────────────── (note: raw results saved in GstatsOutput; see mata GstatsOutput.desc())
gstats
gstats winsor varlist [if] [in] [weight], [by(varlist) cuts(# #) options]
. sysuse auto, clear (1978 automobile data) . gstats winsor price gear_ratio mpg, cuts(5 95) s(_w1) . gstats winsor price gear_ratio mpg, cuts(5 95) by(foreign) s(_w2)
hashsort
hashsort varlist, [options]
. sysuse auto, clear (1978 automobile data) . hashsort -make (note: missing values will be sorted first) . hashsort foreign -rep78, benchmark verbose mlast Parsed by variables; .003 seconds Bijection OK with all integers (i.e. no extended miss val)? Yes. Radix sort on 16-bit hash (8-bits at a time) N = 74; 10 unbalanced groups of sizes 1 to 27 C plugin runtime; 0 seconds Stata reshuffle; 0 seconds Internal gtools runtime; .003 seconds
Bên cạnh, các lệnh trong gói gtools, bạn có thể sử dụng các lệnh trong gói ftools như fcollapse, fegen, fsort, flevelof… để tăng tốc xử lý trong trường hợp dữ liệu lớn.
Tham khảo:
https://gtools.readthedocs.io/en/latest/
https://github.com/sergiocorreia/ftools