3

我正在尝试使用tabulateStata 中的命令来创建频率的时间序列。当我尝试合并tabulate每个日期之后的输出时,就会出现问题。tabulate当所讨论的变量的值不存在观察值时,将不包括 0 作为条目。例如,如果我想计算一个班级中 10 岁、11 岁和 12 岁的学生,如果只代表其中一个组,Stata 可能会输出 (8),因此我们不知道 8 组是哪一组学生属于:可能是 (0,8,0) 或 (0,0,8)。

如果时间序列很短,这不是问题,因为“结果”窗口会显示哪些类别已表示或未表示。我的数据有更长的时间序列。有谁知道强制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;
4

3 回答 3

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

我认为这就是您要追求的(但无法说出您如何使用要生成的矩阵)。

PS我更喜欢将该inlist功能用于以下用途:

replace LT_num = 2 if inlist(splticrm,"AA","AA+","AA-")
于 2011-02-15T17:28:32.447 回答
2

此问题由 解决tabcount。参见 2003 年的论文

http://www.stata-journal.com/article.html?article=pr0011

并在获得链接后下载程序代码和帮助文件search tabcount

于 2013-01-31T14:42:12.803 回答
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');
};
于 2011-02-16T18:34:42.543 回答