这并没有得到太多回应,原因有几个:
您没有显示太多代码。
您没有以特别有用的形式显示数据。无法将图像轻松复制并粘贴到某人的 Stata 中以进行实验。实际上,您的图像显示了不相关的变量和彼此不同版本的变量,因此比我们需要的要复杂得多。
您将问题升级为询问您想知道的最复杂的版本。
您应该更好地解释一个问题。 area 是字符串,因此根本无法计算总计,area2 只是任意整数,因此可以计算总计但没有意义。 “没有任何效果”作为问题报告没有提供信息。对我来说唯一有意义的总数是value。
您需要先简化您的问题,然后再进行构建。
本质似乎是这样的:
* Example generated by -dataex-. To install: ssc install dataex
clear
input str2 country str6 item float year str1 region float value
"A" "barley" 1999 "X" 1
"B" "barley" 1999 "X" 2
"C" "barley" 1999 "Y" 3
"A" "barley" 2000 "X" 4
"B" "barley" 2000 "X" 5
"C" "barley" 2000 "Y" 6
"A" "barley" 2001 "X" 7
"B" "barley" 2001 "X" 8
"C" "barley" 2001 "Y" 9
end
* means by countries: similar variables for other periods
egen mean_9901_c = mean(cond(inrange(year, 1999, 2001), value, .)), by(country item)
* aggregation to regions, but ensure that you don't double count
egen value_region = total(value), by(region item year)
egen tag = tag(region item year)
* means by regions: similar variables for other periods
egen mean_9901_r = mean(cond(tag == 1 & inrange(year, 1999, 2001), value_region, .)), by(region item)
list, sepby(year)
+---------------------------------------------------------------------------------+
| country item year region value mean_9~c value_~n tag mean_9~r |
|---------------------------------------------------------------------------------|
1. | A barley 1999 X 1 4 3 1 9 |
2. | B barley 1999 X 2 5 3 0 9 |
3. | C barley 1999 Y 3 6 3 1 6 |
|---------------------------------------------------------------------------------|
4. | A barley 2000 X 4 4 9 1 9 |
5. | B barley 2000 X 5 5 9 0 9 |
6. | C barley 2000 Y 6 6 6 1 6 |
|---------------------------------------------------------------------------------|
7. | A barley 2001 X 7 4 15 1 9 |
8. | B barley 2001 X 8 5 15 0 9 |
9. | C barley 2001 Y 9 6 9 1 6 |
+---------------------------------------------------------------------------------+
该示例仅显示一项,但代码应该适用于多项。
该示例仅显示了三年的虚假数据,但可以类似地构建其他时期的平均值。
结果会针对它们适用的所有观察结果重复。要仅查看或使用一次结果,请使用 if。例如,1999 年至 2001 年的平均值显示为这些年份(以及其他年份),但if year == 1999 将是一种只查看一次结果的方法。
另请参阅help collapse、help egen 以了解其tag() 功能和this paper。
你的代码出了什么问题
你的问题始于
if area=="Russia" & area=="Ukraine"
它选择在同一观察中area 既是“俄罗斯”又是“乌克兰”的观察,这是不可能的。您需要|(或)运算符,而不是& 运算符,或者以其他方式解决问题。
前缀id 也是错误的。使用by id: 会强制对id 的不同值进行单独计算,这将使标识符的组合变得不可能。