簡體   English   中英

如何計算Stata中某些變量的總和?

[英]How to compute the sum of some variables in Stata?

我的數據集中有 48 個變量:第一個 12 個關注 2000 年,第二個 12 年 2001 年,第三個 12 年 2002 年和第四個 12 年 2003 年。每個單個變量都包含以下值:

ID 變量1 變量2 變量3 ... var12 ... var48
xx 0 0 1 ... 1 ... 0
年年 1 0 0 ... 9 ... 0
Z Z 3 2 1 ... 0 ... 0

現在,我想將前 12 個變量的值的總和收集到另一個名為“tot_2000”的變量中,它應該只包含一個數字(在本例中為 18)。 然后,我必須在剩下的 3 年重復這段話,因此要在直方圖中繪制 4 個變量(“tot_2000”、“tot_2001”、“tot2002”、“tot2003”)。

我正在尋找的是這樣一個變量:

tot_2000
18

以下是如何分兩步執行此操作的解決方案:

* Example generated by -dataex-. For more info, type help dataex
clear
input str2 ID byte(var1 var2 var3 var4)
"xx" 0 0 1 1
"yy" 1 0 0 9
"zz" 3 2 1 0
end

egen row_sum = rowtotal(var*) //Sum each row into a var
egen tot_var = sum(row_sum ) //Sum the row_sum var

* Get the value of the first observation and store in a local macro
local total = tot_var[1]
display `total'

原始問題,由@TheIceBear 和我自己解決。

我有一個數據集,其中包含 12 個變量,其值為 0,1,2.... 像這樣,例如:

ID 變量1 變量2 變量3 ... var12
xx 0 0 1 ... 1
年年 1 0 0 ... 9
Z Z 3 2 1 ... 0

我想創建一個變量,它只是所有值的總和(在本例中為 18),例如:

總變量18

命令是什么?

我的第一個答案

這是另一種方法,如@TheIceBear 對第一個答案的評論中所示。

* Example generated by -dataex-. For more info, type help dataex
clear
input str2 ID byte(var1 var2 var3 var4)
"xx" 0 0 1 1
"yy" 1 0 0 9
"zz" 3 2 1 0
end

mata : total = sum(st_data(., "var1 var2 var3 var4")) 

mata : st_numscalar("total", total)

di scalar(total)
18

這兩個 Mata 命令可以伸縮。

第二個答案

一個完全不同的問題正從評論和編輯中慢慢浮現。 這個問題仍然沒有重點,但這里試圖加強它。

您有各種標識符的月度數據。 您想查看帶有年度總數的條形圖(而不是直方圖)。

您擁有的數據結構或布局不適合在 Stata 中處理此類數據。 你有一個所謂的寬布局,但一個長布局是非常可取的。 然后你的總數可以放在一個變量中進行繪圖。

* fake dataset 
clear
set obs 3 
gen id = word("xx yy zz", _n)

forval j = 1/48 { 
    gen var`j' = _n * `j'
}

* you start here 
reshape long var, i(id) j(time)
gen mdate = ym(1999, 12) + time 
format mdate %tm 
gen year = year(dofm(mdate))

* not clear that you want this, but it could be useful 
egen total = total(var), by(id year)
twoway bar total year, by(id) xla(2000/2003) name(G1, replace)

* this seems to be what you are asking for 
egen TOTAL = total(var), by(year)
twoway bar TOTAL year, base(0) xla(2000/2003) name(G2, replace)

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM