Please Enable JavaScript in your Browser to visit this site

Xử lý dữ liệu

Minh họa tạo bảng tổng hợp kết quả kiểm định thống kê

Sử dụng lệnh table kết hợp với lệnh collect trên Stata 17

Ở hai bài viết trước, chúng ta đã làm quen với câu lệnh table và collect để tạo một bảng tổng hợp cơ bản và xuất kết quả bảng này ra Word. Bài viết này tôi sẽ tiếp tục giới thiệu và minh họa cách sử dụng lệnh collect để từng bước tạo ra được một bảng tổng hợp kết quả kiểm định thống kê được định dạng theo yêu cầu. Quy trình các bước thực hiện tạo bảng tổng hợp kết quả kiểm định thống kê của các biến cũng được mô tả chi tiết.

Dữ liệu

Tôi tiếp tục thực hành trên bộ dữ liệu NHANES-II 1 và xem sơ qua các biến trong bộ dữ liệu.

. webuse nhanes2, clear

. describe highbp age hgb hct iron albumin vitaminc zinc copper lead     ///
>     height weight bmi bpsystol bpdiast tcresult tgresult hdresult

Variable      Storage   Display    Value
    name         type    format    label      Variable label
───────────────────────────────────────────────────────────────────────────────────────────────────────────────
highbp          byte    %8.0g               * High blood pressure
age             byte    %9.0g                 Age (years)
hgb             float   %9.0g                 Hemoglobin (g/dL)
hct             float   %9.0g                 Hematocrit (%)
iron            int     %9.0g                 Serum iron (mcg/dL)
albumin         float   %9.0g                 Serum albumin (g/dL)
vitaminc        float   %9.0g                 Serum vitamin C (mg/dL)
zinc            int     %9.0g                 Serum zinc (mcg/dL)
copper          int     %9.0g                 Serum copper (mcg/dL)
lead            byte    %9.0g                 Lead (mcg/dL)
height          float   %9.0g                 Height (cm)
weight          float   %9.0g                 Weight (kg)
bmi             float   %9.0g                 Body mass index (BMI)
bpsystol        int     %9.0g                 Systolic blood pressure
bpdiast         int     %9.0g                 Diastolic blood pressure
tcresult        int     %9.0g                 Serum cholesterol (mg/dL)
tgresult        int     %9.0g                 Serum triglycerides (mg/dL)
hdresult        int     %9.0g                 High density lipids (mg/dL)

Recode levels

Đầu tiên, tôi thử tạo một bảng tần suất đơn giản như sau:

. #delimit ;
delimiter now ;
. table (var) (highbp),
>    statistic(fvfrequency sex)
>    statistic(fvpercent sex) 
>    statistic(mean age) 
>    statistic(sd age) 
>    nototal;

────────────────────────────┬───────────────────────
                            │   High blood pressure 
                            │          0           1
────────────────────────────┼───────────────────────
Sex=Male                    │                       
  Factor variable frequency │      2,611       2,304
  Factor variable percent   │      43.70       52.65
Sex=Female                  │                       
  Factor variable frequency │      3,364       2,072
  Factor variable percent   │      56.30       47.35
Age (years)                 │                       
  Mean                      │   42.16502    54.97281
  Standard deviation        │   16.77157    14.90897
────────────────────────────┴───────────────────────

. #delimit cr
delimiter now cr

Ở đây, tôi sử dụng tuỳ chọn nototal để bỏ cột total ở bảng tần suất.

Tiếp đến, tôi xem qua các dimension của collection hiện tại qua lệnh collect dims

. collect dims
Collection dimensions
Collection: Table
─────────────────────────────────────────
                   Dimension   No. levels
─────────────────────────────────────────
Layout, style, header, label
                      cmdset   1         
                     colname   3         
                     command   1         
                      highbp   2         
                      result   4         
                     statcmd   4         
                         var   3         

Header, label
                         sex

Style only
                border_block   4         
                   cell_type   4         
─────────────────────────────────────────

Tôi thử lướt qua các giá trị và nhãn của dimension result (được tạo từ tuỳ chọn statistic)

. collect label list result, all
  Collection: Table
   Dimension: result
       Label: Result
Level labels:
 fvfrequency  Factor variable frequency
   fvpercent  Factor variable percent
        mean  Mean
          sd  Standard deviation

Kết quả cho thấy dimension result có 4 level là fvfrequency, fvpercent, mean, và sd. Tương tự như các giá trị của của biến danh mục, tôi có thể phân nhóm hay mã hoá lại (recode) các giá trị của dimension này.

Cụ thể, tôi sử dụng collect recode tạo ra hai level: column1 và column2. Sau đó, tôi gom
fvfrequency và mean vào column1; trong khi fvpercent và sd vào column2.

. #delimit ;
delimiter now ;
. collect recode result fvfrequency = column1
>                    fvpercent   = column2
>                    mean        = column1
>                    sd          = column2;
(12 items recoded in collection Table)

. #delimit cr                           
delimiter now cr
. collect label list result, all
  Collection: Table
   Dimension: result
       Label: Result
Level labels:
     column1  
     column2  
 fvfrequency  Factor variable frequency
   fvpercent  Factor variable percent
        mean  Mean
          sd  Standard deviation

Như vậy, chúng ta thấy hai level mới, column1 và column2 đã xuất hiện ở dimension result bên cạnh các level ban đầu.

Thiết lập bố cục

Sử dụng collect layout để thay đổi bố cục của bảng. Với kết quả từ bảng trên thì dòng vẫn là
var, và cột đầu tiên vẫn là highbp. Tôi có thể lồng hai level column1column2 của dimension result bên dưới dimension highbp, bằng cách khai báo highbp#result[column1 column2] ở column dimension.

. collect layout (var) (highbp#result[column1 column2])
Collection: Table
      Rows: var
   Columns: highbp#result[column1 column2]
   Table 1: 3 x 4

────────────┬───────────────────────────────────────────
            │             High blood pressure           
            │           0                     1         
            │   column1    column2    column1    column2
────────────┼───────────────────────────────────────────
Sex=Male    │      2611   43.69874       2304   52.65082
Sex=Female  │      3364   56.30126       2072   47.34918
Age (years) │  42.16502   16.77157   54.97281   14.90897
────────────┴───────────────────────────────────────────

Ý nghĩa highbp#result[column1 column2]

  • Toán tử # cho biết sự tương tác (lồng) giữa hai dimension, với ý nghĩa rằng dimension đứng sau sẽ được lồng vào dimension đứng trước.
  • result[column1 column2] chỉ định sử dụng hai level có tên là column1column2 của dimension result

Bằng cách thêm các biến khác vào tuỳ chọn statistic(), tôi có thể lập một bảng thống kê mô tả cho nhiều biến. Ở đây, tôi sẽ thực hiện thống kê giá trị trung bình, độ lệch chuẩn cho age, bmi, tcresult, tgresulthdresult; thống kê tần suất cho race, sexhlthstat.

. #delimit ;
delimiter now ;
. table (var) (highbp),
>    statistic(mean age bmi)
>    statistic(sd   age bmi)
>    statistic(fvfrequency sex race hlthstat)
>    statistic(fvpercent   sex race hlthstat)
>    statistic(mean tcresult tgresult hdresult)
>    statistic(sd   tcresult tgresult hdresult)
>    nototal;

───────────────────────────────────┬───────────────────────
                                   │   High blood pressure 
                                   │          0           1
───────────────────────────────────┼───────────────────────
Age (years)                        │                       
  Mean                             │   42.16502    54.97281
  Standard deviation               │   16.77157    14.90897
Body mass index (BMI)              │                       
  Mean                             │   24.20231    27.36081
  Standard deviation               │   4.100279    5.332119
Sex=Male                           │                       
  Factor variable frequency        │      2,611       2,304
  Factor variable percent          │      43.70       52.65
Sex=Female                         │                       
  Factor variable frequency        │      3,364       2,072
  Factor variable percent          │      56.30       47.35
Race=White                         │                       
  Factor variable frequency        │      5,317       3,748
  Factor variable percent          │      88.99       85.65
Race=Black                         │                       
  Factor variable frequency        │        545         541
  Factor variable percent          │       9.12       12.36
Race=Other                         │                       
  Factor variable frequency        │        113          87
  Factor variable percent          │       1.89        1.99
Health status=Excellent            │                       
  Factor variable frequency        │      1,649         758
  Factor variable percent          │      27.61       17.32
Health status=Very good            │                       
  Factor variable frequency        │      1,666         925
  Factor variable percent          │      27.89       21.14
Health status=Good                 │                       
  Factor variable frequency        │      1,572       1,366
  Factor variable percent          │      26.32       31.22
Health status=Fair                 │                       
  Factor variable frequency        │        766         904
  Factor variable percent          │      12.82       20.66
Health status=Poor                 │                       
  Factor variable frequency        │        310         419
  Factor variable percent          │       5.19        9.57
Health status=Blank but applicable │                       
  Factor variable frequency        │         10           4
  Factor variable percent          │       0.17        0.09
Serum cholesterol (mg/dL)          │                       
  Mean                             │   208.7272    229.8798
  Standard deviation               │   47.28725    49.58294
Serum triglycerides (mg/dL)        │                       
  Mean                             │   129.2284    166.0427
  Standard deviation               │   83.92955    109.1998
High density lipids (mg/dL)        │                       
  Mean                             │   49.94449    49.21784
  Standard deviation               │   14.14055    14.54068
───────────────────────────────────┴───────────────────────

. #delimit cr
delimiter now cr

Khi đó, bảng thống kê mô tả cho các biến sẽ như sau:

. #delimit ;
delimiter now ;
. collect recode result fvfrequency = column1
>                    fvpercent   = column2
>                    mean        = column1
>                    sd          = column2;
(64 items recoded in collection Table)

. #delimit cr    
delimiter now cr
. collect layout (var) (highbp#result[column1 column2])

Collection: Table
      Rows: var
   Columns: highbp#result[column1 column2]
   Table 1: 16 x 4

───────────────────────────────────┬───────────────────────────────────────────
                                   │             High blood pressure           
                                   │           0                     1         
                                   │   column1    column2    column1    column2
───────────────────────────────────┼───────────────────────────────────────────
Age (years)                        │  42.16502   16.77157   54.97281   14.90897
Body mass index (BMI)              │  24.20231   4.100279   27.36081   5.332119
Sex=Male                           │      2611   43.69874       2304   52.65082
Sex=Female                         │      3364   56.30126       2072   47.34918
Race=White                         │      5317   88.98745       3748   85.64899
Race=Black                         │       545   9.121339        541   12.36289
Race=Other                         │       113   1.891213         87   1.988117
Health status=Excellent            │      1649   27.60757        758   17.32176
Health status=Very good            │      1666   27.89218        925   21.13803
Health status=Good                 │      1572   26.31843       1366   31.21572
Health status=Fair                 │       766   12.82438        904   20.65814
Health status=Poor                 │       310   5.190022        419   9.574954
Health status=Blank but applicable │        10   .1674201          4   .0914077
Serum cholesterol (mg/dL)          │  208.7272   47.28725   229.8798   49.58294
Serum triglycerides (mg/dL)        │  129.2284   83.92955   166.0427   109.1998
High density lipids (mg/dL)        │  49.94449   14.14055   49.21784   14.54068
───────────────────────────────────┴───────────────────────────────────────────

Định dạng hiển thị số

Ở bài trước, tôi đã sử dụng tuỳ chọn nformat()sformat() của câu lệnh
table để định dạng hiển thị số trong bảng kết quả. Chúng ta cũng có thể sử dụng collect style cell để áp dụng các định dạng số khác nhau cho các ô khác nhau trong bảng kết quả. Lệnh collect style cell sử dụng các dimension và level để đề cập đến các ô trong bảng.

. collect style cell var[sex race hlthstat]#result[column1], nformat(%6.0fc)
. collect style cell var[sex race hlthstat]#result[column2], nformat(%6.1f) sformat("%s%%")
. collect style cell var[age bmi tcresult tgresult hdresult]#result[column1 column2], nformat(%6.1f)
. collect style cell var[age bmi tcresult tgresult hdresult]#result[column2], sformat("(%s)")

. collect preview

───────────────────────────────────┬───────────────────────────────────────
                                   │           High blood pressure         
                                   │          0                   1        
                                   │  column1   column2   column1   column2
───────────────────────────────────┼───────────────────────────────────────
Age (years)                        │     42.2    (16.8)      55.0    (14.9)
Body mass index (BMI)              │     24.2     (4.1)      27.4     (5.3)
Sex=Male                           │    2,611     43.7%     2,304     52.7%
Sex=Female                         │    3,364     56.3%     2,072     47.3%
Race=White                         │    5,317     89.0%     3,748     85.6%
Race=Black                         │      545      9.1%       541     12.4%
Race=Other                         │      113      1.9%        87      2.0%
Health status=Excellent            │    1,649     27.6%       758     17.3%
Health status=Very good            │    1,666     27.9%       925     21.1%
Health status=Good                 │    1,572     26.3%     1,366     31.2%
Health status=Fair                 │      766     12.8%       904     20.7%
Health status=Poor                 │      310      5.2%       419      9.6%
Health status=Blank but applicable │       10      0.2%         4      0.1%
Serum cholesterol (mg/dL)          │    208.7    (47.3)     229.9    (49.6)
Serum triglycerides (mg/dL)        │    129.2    (83.9)     166.0   (109.2)
High density lipids (mg/dL)        │     49.9    (14.1)      49.2    (14.5)
───────────────────────────────────┴───────────────────────────────────────

Ý nghĩa các dòng lệnh

  • Toán tử # ở lệnh đầu tiên sẽ chọn các ô thoả mãn đồng thời cả hai điều kiện.
  • Điều kiện dòng: row dimension var với ba level là sex, race và hlthstat
  • Điều kiện cột: column dimension result với level là column1
  • Việc giải thích toán tử # ở các dòng còn lại có ý nghĩa tương tự như dòng đầu tiên
  • nformat(%6.0fc): định dạng số, không số thập phân và có dấu phẩy ngăn cách hàng nghìn.
  • nformat(%6.1fc): định dạng số, có một số thập phân và có dấu phẩy ngăn cách hàng nghìn.
  • sformat(“%s%%”): thêm kí tự % ở cuối số.
  • sformat(“(%s)”): thêm cặp dấu ngoặc đơn bao quanh số.

Thiết lập nhãn cột

Đoạn chương trình bên dưới sẽ điều chỉnh nhãn hiển thị để bảng nhìn gọn và dễ hiểu hơn.

. collect label dim highbp "Hypertension", modify
. collect label levels highbp 0 "No" 1 "Yes"
. collect style header result, level(hide)
. collect preview

───────────────────────────────────┬──────────────────────────────────
                                   │            Hypertension          
                                   │        No               Yes      
───────────────────────────────────┼──────────────────────────────────
Age (years)                        │   42.2   (16.8)    55.0    (14.9)
Body mass index (BMI)              │   24.2    (4.1)    27.4     (5.3)
Sex=Male                           │  2,611    43.7%   2,304     52.7%
Sex=Female                         │  3,364    56.3%   2,072     47.3%
Race=White                         │  5,317    89.0%   3,748     85.6%
Race=Black                         │    545     9.1%     541     12.4%
Race=Other                         │    113     1.9%      87      2.0%
Health status=Excellent            │  1,649    27.6%     758     17.3%
Health status=Very good            │  1,666    27.9%     925     21.1%
Health status=Good                 │  1,572    26.3%   1,366     31.2%
Health status=Fair                 │    766    12.8%     904     20.7%
Health status=Poor                 │    310     5.2%     419      9.6%
Health status=Blank but applicable │     10     0.2%       4      0.1%
Serum cholesterol (mg/dL)          │  208.7   (47.3)   229.9    (49.6)
Serum triglycerides (mg/dL)        │  129.2   (83.9)   166.0   (109.2)
High density lipids (mg/dL)        │   49.9   (14.1)    49.2    (14.5)
───────────────────────────────────┴──────────────────────────────────

Ở đây,

  • Dòng 1: sử dụng collect label dim highbp để thay đổi nhãn của dimension highbp
  • Dòng 2: sử dụng collect label levels highbp để thay đổi level của dimension highbp
  • Dòng 3: sử dụng collect style header result, level(hide) để ẩn level của một dimension result

Thiết lập nhãn dòng

Sử dụng lệnh collect style row để thay đổi các thiết lập hiển thị dòng của bảng.

  • Tham số stack của câu lệnh sẽ lồng các level của dimension lại với nhau thay vì hiển thị riêng rẽ. Chẳng hạn, level MaleFemale sẽ đứng cạnh nhau bên dưới nhãn Sex của dimension Sex.
  • Tuỳ chọn nobinder sẽ bỏ dấu = xuất hiện ở giữa dimension và level của nó.
  • Tuỳ chọn spacer sẽ thêm một khoảng trắng giữa các level được tạo bởi các tuỳ chọn
    statistic() khác nhau.
. collect style row stack, nobinder spacer
. collect style cell border_block, border(right, pattern(nil))
. collect preview

─────────────────────────────────────────────────────────────
                                       Hypertension          
                                   No               Yes      
─────────────────────────────────────────────────────────────
Age (years)                   42.2   (16.8)    55.0    (14.9)
Body mass index (BMI)         24.2    (4.1)    27.4     (5.3)
                                                             
Sex                                                          
  Male                       2,611    43.7%   2,304     52.7%
  Female                     3,364    56.3%   2,072     47.3%
Race                                                         
  White                      5,317    89.0%   3,748     85.6%
  Black                        545     9.1%     541     12.4%
  Other                        113     1.9%      87      2.0%
Health status                                                
  Excellent                  1,649    27.6%     758     17.3%
  Very good                  1,666    27.9%     925     21.1%
  Good                       1,572    26.3%   1,366     31.2%
  Fair                         766    12.8%     904     20.7%
  Poor                         310     5.2%     419      9.6%
  Blank but applicable          10     0.2%       4      0.1%
                                                             
Serum cholesterol (mg/dL)    208.7   (47.3)   229.9    (49.6)
Serum triglycerides (mg/dL)  129.2   (83.9)   166.0   (109.2)
High density lipids (mg/dL)   49.9   (14.1)    49.2    (14.5)
─────────────────────────────────────────────────────────────

Xuất kết quả ra file Word

Khi đã hài lòng với dạng hiển thị của bảng, tôi có thể xuất kết quả ra file Word. Sử dụng lệnh putdocx để thêm tiêu đề, các đề mục và những nội dung mô tả cần thiết trước khi chèn
bảng vừa tạo. Cuối cùng, tôi sử dụng lệnh putdocx collect để xuất bảng kết quả ra tài liệu.

. putdocx begin
. putdocx paragraph, style(Title)
. putdocx text ("Hypertension in the United States")
. putdocx paragraph, style(Heading1)
. putdocx text ("The National Health and Nutrition Examination Survey (NHANES)")
. putdocx paragraph
. putdocx text ("Hypertension is a major cause of morbidity and mortality in ")
. putdocx text ("the United States. This report will explore the predictors ")
. putdocx text ("of hypertension using the NHANES dataset.")
. collect style putdocx,  layout(autofitcontents) ///
>                     title("Table 1: Descriptive Statistics by Hypertension Status")
. putdocx collect
(collection Table posted to putdocx)
. putdocx save Table3.docx, replace
successfully replaced "D:/GitHub/TNS/premium/Table3.docx"

Tổng kết

Để tạo các bảng tổng hợp kiểm định thống kê cho các biến, đầu tiên tạo các bảng đơn giản bằng cách sử dụng lệnh table với tuỳ chọn statistic(). Sau đó,

  • sử dụng collect label để đổi tên các nhãn của các dimension và level,
  • sử dụng collect style row để tinh chỉnh nhãn của các dòng,
  • sử dụng collect style cell để loại đường kẻ đứng.

Sau đó, sử dụng collect style putdocx và putdocx collect để điều chỉnh và xuất
bảng tổng hợp sang Word.

Ngoài ra, một số câu lệnh hay được sử dụng trong bài viết như:

  • collect recode để mã hoá các level của một dimension
  • collect layout để thiết lập bố cục bảng
  • collect style cell để thực hiện các định dạng số

Bài viết được tổng hợp từ The Stata Blog 2

Tài liệu tham khảo


  1. McDowell A, Engel A, Massey JT, Maurer KPlan and operation of the Second National Health and Nutrition Examination Survey, 1976-1980Vital Health Stat 11981;(15):1-144PMID:
    7344293.↩︎
  2. Customizable tables in Stata 17, part 3: The classic table 1 tại:
    https://blog.stata.com/2021/06/24/customizable-tables-in-stata-17-part-3-the-classic-table-1/↩︎
Back to top button