Stata14生成变量时出现错误(198)求助:变量语法排查
ncskew Hey there, let's figure out why you're hitting error (198) in Stata 14 when trying to generate your ncskew variable. I'll break down the issues in your code and walk you through fixes step by step.
First: What's Error 198?
Stata's error 198 almost always points to a syntax issue—think mismatched parentheses, invalid operator usage, or incorrect handling of functions/subscripts. Let's start with your original code:
g ncskew =(-(([_n])*([_n-1])^(1.5)*(sum(returns^3))))/// /(([_n-1])*([_n-2])*(sum(returns^2)^(1.5))
Key Issues in Your Code
Mismatched Parentheses
Your code is missing one closing parenthesis at the very end. The entire denominator is wrapped in an opening parenthesis that never gets closed—this is a direct trigger for error 198.Confusing
_nvs_N
You're using[_n](the index of the current observation/row) instead of_N(the total number of observations in your sample/group). For calculating skewness, you need the sample size, not the current row number. Using_nhere will give you nonsensical values even if the syntax works.sum()is Not What You Think
Stata'ssum()function calculates a cumulative sum (running total) row-by-row, not the total sum of the entire sample. For the global sum ofreturns^2andreturns^3, you need to usetotal()oregen total()instead.Potential Division by Zero
When your sample size is less than 3,(_N-2)becomes 0 or negative, which will throw a division-by-zero error. We'll add a guard clause for this.
Corrected Code (Whole Sample)
If you're calculating ncskew for the entire dataset, use this:
// Calculate total sums of returns squared and cubed egen sum_r2 = total(returns^2) egen sum_r3 = total(returns^3) // Generate ncskew with correct sample size (_N) and valid syntax gen ncskew = . replace ncskew = (-(_N * (_N - 1)^1.5 * sum_r3)) / ((_N - 1) * (_N - 2) * sum_r2^1.5) if _N >= 3 // Clean up temporary variables drop sum_r2 sum_r3
Corrected Code (Grouped by Firm/Year)
If you need to calculate ncskew for groups (e.g., firm-year panels), use bysort to apply the calculation per group:
// Calculate group-level sums and sample size bysort firm year: egen sum_r2 = total(returns^2) bysort firm year: egen sum_r3 = total(returns^3) bysort firm year: gen group_n = _N // Generate grouped ncskew gen ncskew = . replace ncskew = (-((group_n) * (group_n - 1)^1.5 * sum_r3)) / ((group_n - 1) * (group_n - 2) * sum_r2^1.5) if group_n >= 3 // Clean up temporary variables drop sum_r2 sum_r3 group_n
Quick Verification
After running the corrected code, you can cross-check the result against Stata's built-in skewness statistic:
summarize returns, detail // Your ncskew should equal -r(skewness) (since ncskew is defined as negative skewness)
内容的提问来源于stack exchange,提问作者Jack B

