2011-02-15 23 views
3

我试图在Stata中使用tabulate命令来创建时间序列的频率。当我在运行每个日期之后尝试合并tabulate的输出时,会出现问题。当所观察变量的值不存在观察值时,tabulate将不包括0作为条目。例如,如果我想在一个班上计算10,11和12岁儿童的三年时间,Stata可能会输出(8),如果只有其中一个团队有代表,因此我们不知道哪一个团队8学生属于:可能是(0,8,0)或(0,0,8)。如何获得Stata在列表中报告零数

如果时间序列较短,“结果”窗口显示哪些类别未被表示,则这不是问题。我的数据有更长的时间序列。有谁知道强制Stata在这些表中包含零的解决方案/方法吗?我的代码的相关部分如下:

# delimit; 
set more off; 
clear; 
matrix drop _all; 
set mem 1200m; 
cd ; 
global InputFile "/Users/.../1973-2010.dta"; 
global OutputFile "/Users/.../results.txt"; 

use $InputFile; 
compress; 

log using "/Users/.../log.txt", append; 

gen yr_mn = ym(year(datadate), month(datadate)); 
la var yr_mn "Year-Month Date" 

xtset, clear; 
xtset id datadate, monthly; 

/*Converting the Ratings Scale to Numeric*/; 
gen LT_num = .; 
replace LT_num = 1 if splticrm=="AAA"; 
replace LT_num = 2 if (splticrm=="AA"||splticrm=="AA+"||splticrm=="AA-"); 
replace LT_num = 3 if (splticrm=="A"||splticrm=="A+"||splticrm=="A-"); 
replace LT_num = 4 if (splticrm=="BBB"||splticrm=="BBB+"||splticrm=="BBB-"); 
replace LT_num = 5 if (splticrm=="BB"||splticrm=="BB+"||splticrm=="BB-"); 
replace LT_num = 6 if (splticrm=="B"||splticrm=="B+"||splticrm=="B-"); 
replace LT_num = 7 if (splticrm=="CCC"||splticrm=="CCC+"||splticrm=="CCC-"); 
replace LT_num = 8 if (splticrm=="CC"); 
replace LT_num = 9 if (splticrm=="SD"); 
replace LT_num = 10 if (splticrm=="D"); 

summarize(yr_mn); 
local start = r(min); 
local finish = r(max); 

forv x = `start'/`finish' {; 
    qui tab LT_num if yr_mn == `x', matcell(freq_`x'); 
}; 

log close; 

回答

2

你想要的不是tab命令的选项。如果您想要将结果显示在屏幕上,则可以成功使用table ..., missing

取而代之的是循环的,你可以尝试以下方法,我认为这将满足您的需要:

preserve 
gen n = 1 // (n could be a variable that indicates if you want to include the row or not; or just something that never ==.) 
collapse (count) n , by(LT_num yr_mn) 
reshape wide n, i(yr_mn) j(LT_num) 
mkmat _all , matrix(mymatname) 
restore 
mat list mymatname 

我认为这是你以后打算什么(但不能告诉你如何使用您尝试生成的矩阵)。

P.S.我更喜欢使用inlist功能,例如:

replace LT_num = 2 if inlist(splticrm,"AA","AA+","AA-") 
+0

感谢您的快速响应。 – 2011-02-16 18:23:47

0

这是我使用的解决方案。 Keith's可能会更好,我将在未来探索他的解决方案。

我将行标签(使用matrow)保存在向量中,并将其用作初始化为零的正确维的矩阵的索引。这样我可以将每个频率放置在矩阵中的正确位置,并保留所有的零。在“local finish = r(max)”之后,解决方案遵循上述代码。 [注意,我包括计数器,以消除所述第一观察其是空的该变量。]

local counter=0; 
forv x = `first'/`last' {; 
tab LT_num if yr_mn == `x', matrow(index_`x') matcell(freq_`x'); 
local rows = r(r); /*r(r) is number of rows for tabulate*/; 

if `rows'!=0{; 
    matrix define A_`x'=J(10,1,0); 
    forv r=1/`rows'{; 
     local a=index_`x'[`r',1]; 
     matrix define A_`x'[`a',1]=freq_`x'[`r',1]; 
    }; 
}; 
else {; 
    local counter=`counter'+1; 
}; 
}; 


local start=`first'+`counter'+1; 
matrix define FREQ = freq_`start'; 

forv i = `start'/`last' {; 
    matrix FREQ = (FREQ,A_`i'); 
};