TẠO BỘ SỐ LIỆU MỚI TRONG STATA
Nhập trực tiếp vào khung Data Editor của cửa sổ Stata.
Nếu giá trị đầu tiên của biến là số thì biến đó được quy định là numerical variable.
Nếu biến đó nhập là chuỗi thì sẽ quy định là chuỗi
Các lệnh sử dụng sau khi tạo biến mới bao gồm
XÁC ĐỊNH CÁC SUBSET DATA CHO BỘ DỮ LIỆU
list in 1/20
Liệt kê các quan sát từ 1-20
Xếp thứ tự biến pop. Sau đó liệt kê các quan sát từ quan sát cuối trở lên 4 quan sát.
. sum
if pop< 20000
Variable |
Obs
Mean
Std. Dev.
Min
Max
-------------+--------------------------------------------------------place |
0
pop |
12
2467.158
3435.521
30.1
11100.3
unemp |
10
12.26
4.44877
7
19.6
mlife |
12
74.225
1.728965
70.2
75.8
flife |
12
80.68333
1.0116
78
81.8
Tóm tắt số liệu với các quan sát có pop < 20000
.
sum if place !="Canada"
Variable
Obs
Mean
Std. Dev.
Min
Max
3435.521
30.1
11100.3
place 0
pop
12
2467.158
unemp 10
12.26 4.44877
7
19.6
mlife 12
74.225 1.728965
70.2
75.8
flife 12
80.68333
1.0116 78
81.
Tóm tắt số liệu với các quan sát có place khác với chữ Canada.
Lưu ý là với biến chuỗi có thể sử áp dụng tất cả các dấu toán học
.
sum unemp mlife
if
Variable
Obs
pop >
100
& pop <
20000
Mean
Std. Dev.
Min
unemp
10
12.26
4.44877
7
19.6
mlife
10
74.92
.6051633
73.9
75.8
Max
Tóm tắt unemp và mlife chỉ ở quan sát có pop> 100 và < 20000.
. list if unemp< 9 |( mlife>=75.4 & flife>= 81.4)
place
pop
unemp
8.
Manitoba
1137.5
8.5
9.
Saskatchewan
10.
Alberta
11.
British Columbia
1015.6
2747
mlife flife
75
7
8.4
75.5
3766 9.8
80.8
75.2
81.8
81.4
75.8
81.4
Dấu ngoặc đơn chỉ rằng các hàm toán học trong ngoặc phải được ưu tiên trước.
TẠO VÀ THAY BIẾN MỚI
Lệnh clonevar
. clonevar mompraise = R3483600
Lệnh clonevar có đặc điểm là: đơn giản, giữ giá trị mất theo định dạng của biến cũ,
và giữ được nhãn giá trị cho biến mới.
Lệnh generate
. gen gap = flife- mlife
. list mlife flife gap
+--------------------------+
| mlife
flife
gap |
|--------------------------|
1. |
75.1
81.1
6 |
2. |
73.9
79.8
5.900002 |
3. |
74.8
81.3
6.5 |
4. |
74.2
80.4
6.200005 |
5. |
74.8
80.6
5.799995 |
. format gap %4.1f
. list mlife flife gap
+---------------------+
| mlife
flife
gap |
|---------------------|
1. |
75.1
81.1
6.0 |
2. |
73.9
79.8
5.9 |
3. |
74.8
81.3
6.5 |
4. |
74.2
80.4
6.2 |
5. |
74.8
80.6
5.8 |
Tạo biến mới gap là hiệu số giữa flife và mlife. Biến gap có số thập phân 8 chữ số.
Để rút ngắn cách trình bày biến gap thành hai chữ số thập phân dùng lệnh format.
%4.1f nghĩa là gap định dạng 4 chữ số và 1 số thập phân đằng sau. Tuy nhiên định
dạng này không thay đổi giá trị của gap thành hai chữ số thập phân. Bản chất của
gap vẫn là 8 chữ số thập phân.
Có 3 định dạng chữ số trong Stata:
%w.dg: định dạng số chung (general) trong đó w là độ rộng tổng hoặc là số cột
trình bày và d chính là số thập phân tối thiểu sau dấu thập phân.
%w.df: định dạng chữ số cố định (fixed), trong đó w chính là tổng độ rộng hoặc số
cột trình bày và d chính là số thập phân cố định sau dấu thập phân.
%w.de: chính là định dạng chữ số lũy thừa (exponential) trong đó w chính là độ
rộng cột hoặc số cột trình bày và d là số thập phân cố định theo sau dấu thập phân.
Mặc dù định dạng chữ số có khác nhau nhưng giá trị bên trong của nó vẫn khơng
thay đổi. Các phép tính vẫn tác dụng trên giá trị gốc chứ không phải trên định
dạng.
. gen caseID = _n
Tạo ra biến caseID là số thứ tự quan sát từ thấp đến cao (1 đến n)
Lệnh replace
Lệnh replace thay đổi giá trị của biến chứ không tạo biến mới như lệnh generate.
. gen type=1
. replace type=2 if place=="Yukon" | place =="Northwest Territories"
(2 real changes made)
. replace type=3 if place =="Canada"
(1 real change made)
Lệnh replace còn phối hợp với lệnh gen tạo ra biến phân loại mới
Lệnh egen
Lệnh egen (extension of generate) giúp tạo ra biến có ln hàm tốn học trong đó
Zscore là biến sẽ có các giá trị chuẩn hóa của biến x (trung bình =0 , độ lệch chuẩn
=1)
Biến sum là biến tổng hàng các giá trị của bốn biến x, y, z, w.
Biến xrank là biến giữ thứ bậc các giá trị của x trong đó xrank = 1 cho giá trị x cao
nhất và xrank=2 cho giá trị thứ cao thứ hai v.v.
Tạo biến var4 là tổng điểm hàng của các biến var1, var3 và var3
Tạo biến mean chính là trung bình hàng của 3 biến var1 var2 var3
Lệnh mvdecode
Thay các giá trị 0 trong biến thành missing (.)
SỬ DỤNG VÒNG LẶP (LOOP)
NỐI VÀ GHÉP TẬP TIN SỐ LIỆU
Nối tập tin số liệu (append data)
Nối tập tin số liệu là nối hai file có cùng biến nhưng khác số quan sát để tạo
thành một tập tin duy nhất. Nguyên tắc của nối tập tin số liệu như sau:
----- before merge ----Bộ số liệu
master
Tên tập tin
data1
Tên biến số
Số quan sát
----- after merge -----
using
data2
ID X Y
data3
ID X Y
ID X Y
1 7 10
4
13 15
1
7 10
2
8 11
5
14 16
2
8 11
3
9 12
3
9 12
4
13 15
5
14 16
insheet using Ch1-4data2.txt
Chuyển file Ch1-4data2.txt (file dạng text) vào bộ nhớ Stata
list
save Ch1-4data2 , replace
Lưu file Ch1-4data2.txt thành dạng Ch1-4data2.dta
insheet using Ch1-4data1.txt , clear
// now that we have a Stata-formatted file ready to append, we next
// start with a dataset in memory (combining the insheet and clear
// commands)
list
append using Ch1-4data2
// append data2 on end of data1
list
save Ch1-4data3 , replace
//
save the combined dataset out to a new file
Ghép tập tin số liệu (merge data)
Ghép tập tin số liệu nghĩa là ghép các biến số của cùng một quan sát từ hai
hay nhiều tập tin số liệu với nhau.
Ghép tập tin số liệu thường được sử dụng trong nghiên cứu theo dõi khi một
đối tượng có nhiều hồ sơ trong các đợt khám sức khỏe khác nhau trong q trình
theo dõi.
Có nhiều dạng ghép tập tin số liệu
Ghép 1:1: Trong cách ghép này chúng ta ghép hai tập tin có các biến số khác nhau.
Quan sát thứ nhất của tập tin chủ (tập tin trong bộ nhớ) sẽ được ghép với quan sát
thứ nhất của tập tin hiện hành, và cứ như thế tiếp tục cho đến khi hết quan sát.
Nguyên tắc ghép như sau:
----- before merge ----master
using
data1
data4
----- after merge ----data5
ID X Y
Z
ID X Y Z
1
7
10
17
1
7 10 17
2
8
11
18
2
8 11 18
3
9
12
19
3
9 12 19
.
.
20
.
20
Lệnh merge sẽ ghép các quan sát tương ứng giữa tập tin trong bộ nhớ (hay còn gọi
là tập tin chủ-master) và tập tin hiện hành trong đĩa C (hay còn gọi là tập tin đang
sử dụng-using) thành một quan sát duy nhất.
use "E:\DE TAI\DE TAI DA HOAN THANH\chi tan.dta", clear
Mở tập tin chitan trong thư mục E:\DE TAI\DE TAI DA HOAN THANH
list
Liệt kê tập tin chitan (bắt buộc để Stata ghi nhớ tập tin này là tập tin master)
use "E:\DE TAI\DE TAI DA HOAN THANH\detaichiloan.dta", clear
Mở tập tin detaichiloan trong thư mục E:\DE TAI\DE TAI DA HOAN THANH
list
Liệt kê tập tin detaichiloan (bắt buộc để Stata ghi nhớ tập tin này là tập tin using)
merge 1:1 _n using "E:\DE TAI\DE TAI DA HOAN THANH\chi tan.dta"
Ghép tập tin detaichiloan với tập tin chitan. "_n" tượng trưng cho biến số trong
Stata đối với số thứ tự hàng.
save fileghep , replace
Lưu tập tin ghép dưới tên fileghep
CHUYỂN ĐỔI GIỮA BIẾN CHUỖI VÀ BIẾN SỐ
Tạo biến số từ biến chuỗi
destring d_income, gen(inc_pct_num) ignore("$")
Tạo biến inc_pct là biến kiểu số từ biến chuỗi d_income trong đó loại bỏ (ignore)
các kí tự đặc biệt của biến d_income.
destring inc_pct, gen(inc_pct_num) percent force
Tạo biến inc_pct_num là biến số từ biến inc_pct dạng chuỗi trong đó các giá trị của
biến inc_pct_num sẽ ở dưới dạng phần trăm (percent).
Option force dùng trong trường hợp nếu không thể chuyển những giá trị của biến
chuỗi thành dạng số thì Stata sẽ chuyển những giá trị này thành những giá trị mất.
encode city, gen(citynum)
Tạo biến kiểu số citynum từ biến kiểu chuỗi city trong đó các giá trị của biến
citynum sẽ được gán nhãn gồm các ký tự đầu tiên trong các giá trị của biến city.
Giá trị 1 của biến citynum sẽ được gán cho giá trị đầu tiên theo thứ tự abc của biến
city, và cứ tiếp tục như vậy.
Trong trường hợp biến chuỗi có hầu hết giá trị là số chỉ có một giá trị là chữ như
trường hợp biến sibling có giá trị “4 OR more”, có thể sử dụng hàm real để chuyển
giá trị “4 OR more” thành giá trị mất. Khi đó biến sibnum là biến mới kiểu số có
một giá trị mất.
Tạo biến chuỗi từ biến số
decode citynum2, gen(cityname)
Tạo biến số cityname kiểu chuỗi từ các giá trị của biến kiểu số citynum2. Biến kiểu
số citynum2 phải được dán nhãn thì khi đó các nhãn của citynum2 mới trở thành
giá trị cho biến cityname.
CHUYỂN ĐỔI GIỮA BIẾN NGÀY THÁNG VÀ
BIẾN CHUỖI DẠNG NGÀY
Chuyển đổi ngày thường
text
Code
Output
15/1/2015
gen mydate=date(text, "MDY")
15feb2015
2015/1/15
gen mydate=date(text, "YMD")
15feb2015
201502
gen mydate=date(text, "MY")
1feb2015
1/15/08
gen mydate=date(text,"MDY",1999)
15jan1908
1/15/08
gen mydate=date(text,"MDY",2019)
15jan2008
1/15/51
gen mydate=date(text,"MDY",2000)
15jan1951
1/15/01
gen mydate=date(text,"MDY",2050)
15jan2001
1/15/00
gen mydate=date(text,"MDY",2050)
15jan2000
20060125
gen mydate=date(text, "YMD")
25jan2006
060125
gen mydate=date(text, "20YMD")
25jan2006
Ví dụ:
clear
input str9 text
"15/1/2015"
end
Nhập dữ liệu dạng chuỗi
gen mydate=date(text, "DMY")
Chuyển biến dạng chuỗi thành ngày
format mydate %td
Thay đổi định dạng hiển thị
Chuyển từ ngày thành các dạng tần suất
From daily to
Code
weekly
gen weekly_date = wofd(daily_date)
Monthly
gen monthly_date = mofd(daily_date)
Quarterly
gen qyarterly_date = qofd(daily_date)
Yearly
gen year = year(daily_date)
Example using some data
* Enter example data
clear
input str9 text
"15/1/2015"
end
* Now convert the variable text to Stata date
gen daily_date=date(text, "DMY")
format daily_date %td
* Create a weekly date
gen weekly_date = wofd(daily_date)
format weekly_date %tw
* Create a monthly date
gen monthly_date = mofd(daily_date)
format monthly_date %tm
* Create a quarterly date
gen quarterly_date = qofd(daily_date)
format quarterly_date %tq
* Create a yearly date
gen year = year(daily_date)
From other frequencies to daily
If we already have dates in weekly, monthly, or quarterly frequencies, we can
convert them back to daily dates. The second column in the following table
provides an example of a given format in which the date is already recorded, and
the third column presents the code which shall create a daily date. To see the codes
in action, download this do file and execute. The file extension should be changed
from doc to do after download.
From
given_date
Code
weekly
2018w46
gen daily_date = dofw(given_date)
Monthly
2018m11
gen daily_date = dofm(given_date)
Quarterly
2018q4
gen daily_date = dofq(given_date)
Yearly
2018
gen daily_date = dofy(given_date)
Complex Conversions
If we already have dates in weekly, monthly, or quarterly frequencies, we can
convert them back to daily dates and then to other frequencies. The second column
in the following table provides an example of a given format in which the date is
already recorded, and the third column presents the code which shall convert the
date to the desired frequency.
From
given_date
Code
Weekly to
monthly
2018w46
gen monthly_date = dofm(dofw(given_date))
Monthly to
weekly
2018m11
gen weekly_date = dofw(dofm(given_date))
Quarterly
to monthly
2018q4
gen monthly_date = dofm(dofq(given_date))
Monthly to
quarterly
2018m11
gen quarterly_date = qofd(dofm(given_date))
Weekly to
quarterly
2018w46
gen quarterly_date = qofd(dofw(given_date))
Quarterly
to Weekly
2018q4
gen weekly_date = dofw(dofq(given_date))
Ví Dụ 1: Ngày tháng với 4 số cho năm
input str10 date
20jan2007
06sept2001
21june2004
04july2006
6aug2005
end
list
+------------+
|
date |
|------------|
1. | 20jan2007 |
2. | 06sept2001 |
3. | 21june2004 |
4. | 04july2006 |
5. | 6aug2005 |
gen date2 = date(date, "DMY")
format date2 %td
Hai lệnh date và format được sử dụng để chuyển date dạng chuỗi thành date
dạng số. Cần xác định thông tin thời gian-ngày được format trong chuỗi. Sử dụng
chữ viết hoa cho day, month và year (“DMY”) nhưng chữ thường nếu muốn xác
định hours, minutes hoặc seconds (“DMYhms”).
Câu lệnh đầu tiên tạo biến date mới và chuyển chuỗi thành mã số thích hợp
đối với biến date (nghĩa là số ngày từ ngày 1/1/1960 cho đến ngày đang chuyển).
Dữ liệu của chúng ta theo thứ tự day, month, year, do đó chúng ta sử dụng “dmy”
(hoặc “DMY”) với lệnh date(…).
Lệnh thứ hai định dạng giá trị số để khi Stata trình bày date, nó sẽ ở dạng dễ
cho con người đọc. Lưu ý là khi sử dụng lệnh list để trình bày dữ liệu thì mặc dù
hiển thị tương tự như chuỗi nhưng bản chất nó đã là số.
+------------------------+
|
date
date2 |
|------------------------|
1. | 20jan2007 20jan2007 |
2. | 06sept2001 06sep2001 |
3. | 21june2004 21jun2004 |
4. | 04july2006 04jul2006 |
5. | 6aug2005 06aug2005 |
+------------------------+
Ở trên, dữ liệu chuỗi date đã được định dạng day, month, year với khơng có
ký tự ngăn cách các thành phần của date. Tuy nhiên Stata có thể xử lý rất nhiều
dạng định dạng và có ký tự ngăn cách. Ví dụ dữ liệu có dạng “20-jan-2007”,
“20/jan/2007”, hoặc “20.jan.2007” thì câu lệnh trên vẫn có thể áp dụng cho những
dạng này mà khơng có thay đổi gì. Stata sẽ thậm chí xử lý cả những dates nhập có
dấu cách trong khi các date cịn lại khơng có dấu cách. Chúng ta cũng có thể thay
đổi thứ tự thành phần của date được liệt kê, chúng ta chỉ cần thay đổi thứ tự chữ
được sử dụng trong câu lệnh (ví dụ year, month, day có thể xác định “YMD”).
Date có thể cũng có thể là dạng số ví dụ 20-Jan-2007 có thể trình bày là 201-2007 và thậm chí là 20012007. Lưu ý rằng tất cả các date dạng số được nhập mà
khơng có dấu cách, bạn phải đảm bảo rằng đối với ngày và tháng chỉ có 1 chữ số
(ví dụ 1 cho tháng giêng) phải có số 0 thêm vào.
Case 2: Dates with two-digit and four-digit values for year, with all two-digit dates
in the same century.
The above example assumed that the values for year were listed in a four digit
format (e.g. 2004), however, this is not always the case. The data below contains
dates listed with only two digits, assuming that I know these dates came either
from the 20th (e.g. 1907) or 21st century (e.g. 2007), I can tell Stata to treat the
years as though they are four digit values. To do this I add either “19” or “20” in
front of the Y in the part of the command that gives Stata the order in which the
values appear. For example, for dates listed day, month, year, the specifcation is
“DM20Y”. In the data below, notice that the last two dates both contain four-digit
years (2005 and 1999); this is fine — the only restriction is that the entries with
two-digit values for year all come from the same century.
input str14 date
20jan07
06sept01
21june04
04july06
6august05
6august2005
20june1999
end
list
+-------------+
|
date |
|-------------|
1. |
20jan07 |
2. |
06sept01 |
3. |
21june04 |
4. |
04july06 |
5. | 6august05 |
|-------------|
6. | 6august2005 |
7. | 20june1999 |
+-------------+
The command to create a new numeric date variable from a string variable and
format the new variable so it displays as a date are:
gen date2 = date(date, "DM20Y")
format date2 %td
Note that for dates in the 20th century (e.g. 1997) the command is “DM19Y”.
If you list the data, you should see the following:
list date date2
+-------------------------+
|
date
date2 |
|-------------------------|
1. |
20jan07 20jan2007 |
2. |
06sept01 06sep2001 |
3. |
21june04 21jun2004 |
4. |
04july06 04jul2006 |
5. | 6august05 06aug2005 |
|-------------------------|
6. | 6august2005 06aug2005 |
7. | 20june1999 20jun1999 |
+-------------------------+
As with the first example, the dates can be formatted in a variety of ways, order of
the components does not mater, but the 19 or 20 always precedes the Y.
Case 3: Dates with two-digit and four-digit values for year, all two-digit dates
are not in the same century or not from the 20th or 21st century.
In case 2 we assumed that all the dates with two-digit values for year were from
the same century, and that all of the dates with two-digit values for year fall in
either the 20th or 21st centuries. In this example, we will tell Stata the most recent
year in which the data could appear, and Stata will assign the centuries so that all
dates occur before that year. An example of when this be useful is if I know the
values below are birth dates for currently living individuals. Since they are
currently living, I know that none of them was born after the current year (2007),
and it is unlikely that the value “07” in the year is 1907 rather than 2007 (note that
this sort of information is highly dependent on the data, so you will want to check
any assumptions you make against what you actually know about your data). This
would also come in handy if your 2-digit year values all come from an earlier
century. For example, if all your dates are from the 1700s, giving Stata 1799 as the
last possible year will result in all two digit dates begin assigned to the eighteenth
century (i.e. 84 would be interpreted as 1784).
input str18 date
20jan2007
06sept1985
21june04
4july90
9jan1999
6aug99
19august2003
end
list
+--------------+
|
date |
|--------------|
1. |
20jan2007 |
2. | 06sept1985 |
3. |
21june04 |
4. |
4july90 |
5. |
9jan1999 |
|--------------|
6. |
6aug99 |
7. | 19august2003 |
+--------------+
The command to create a new numeric date variable from a string variable and
format the new variable so it displays as a date is:
gen date2 = date(date, "DMY", 2007)
format date2 %td
If you list the data you should see the following:
list date date2
+-------------------------+
|
date
date2 |
|-------------------------|
1. |
20jan07 20jan2007 |
2. |
06sept01 06sep2001 |
3. |
21june04 21jun2004 |
4. |
04july06 04jul2006 |
5. | 6august05 06aug2005 |
|-------------------------|
6. | 6august2005 06aug2005 |
7. | 20june1999 20jun1999 |
+-------------------------+
Converting Strings to Dates
If you've been given a date in string form, such as "November
3, 2010", "11/3/2010" or "2010-11-03 08:35:12" it can be
converted using the date function. The date function takes two
arguments, the string to be converted, and a series of letters
called a "mask" that tells Stata how the string is structured. In a
date mask, Y means year, M means month, D means day
and # means an element should be skipped.
Thus the mask MDY means "month, day, year" and can be
used to convert both "November 3, 2010" and "11/3/2010". A
date
like
"2010-11-03
08:35:12"
requires
the
mask YMD### so that the last three numbers are skipped. If
you are interested in tracking the time of day you need to
switch to the clock function and the %tc format so time is
measured in milliseconds rather than days, but they are very
similar.
To see this in action, type (or copy and paste) the following
into Stata:
use />This is an example data set containing the above dates
as dateString1, dateString2and dateString3. To convert them to
Stata dates do the following:
gen
date1=date(dateString1,"MDY")
gen
date2=date(dateString2,"MDY")
gen date3=date(dateString3,"YMD###")
Note that the mask goes in quotes.
Converting Numbers to Dates
Another common scenario gives you dates as three separate
numeric variables, one for the year, one for the month and one
for the day. The year, month and day variables in the example
data set contain the same date as the others but in this format.
To convert such dates to Stata dates, use the mdy function. It
takes three numeric arguments: the month, day and year to be
converted.
gen date4=mdy(month,day,year)
Formatting Date Variables
While the four date variables you've created are perfectly
functional dates as far as Stata is concerned, they're difficult
for humans to interpret. However, the %td format tells Stata to
print them out as human readable dates: