我的資料集中有 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 |
uj5u.com熱心網友回復:
原始問題,由@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)
uj5u.com熱心網友回復:
以下是如何分兩步執行此操作的解決方案:
* 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'
轉載請註明出處,本文鏈接:https://www.uj5u.com/qukuanlian/506946.html