赞
踩
sum()
和total()
,但由于历史原因,二者在一些场景下可能会产生意料之外、甚至错误的结果,特此撰文。直接上代码:
* 产生一个变量v1 clear all input v1 1 2 2 3 4 end * 用`gen`产生求和变量 gen gs = sum(v1) gen gt = total(v1) // 报错:unknown function total() * 用`egen`产生求和变量 egen egs = sum(v1) egen egt = total(v1) * 结果: v1 gs egs egt 1 1 12 12 2 3 12 12 2 5 12 12 3 8 12 12 4 12 12 12
原因
- help
sum()
sum(x): the running sum of x, treating missing values as zero.For example, following the command generatey=sum(x)
, the jth observation on y contains the sum of the first through jth observations on x. See [D] egen for an alternative sum function, total(), that produces a constant equal to the overall sum.- help
total()
找不到这个函数,只有一个total
(“produces estimates of totals, along with standard errors”)(注意区别)。也就是说,total()
必须在egen
中使用,表示overall sum。- 如上, 特别值得注意的是,在
egen
中,sum()
和total()
得到的结果相同,但在gen
中则不同。
- 官方说明:
help whatsnew8to9
The following egen functions have been renamed:
old name new name
any() anyvalue()
eqany() anymatch()
neqany() anycount()
rfirst() rowfirst()
rlast() rowlast()
rmean() rowmean()
rmin() rowmin()
rmiss() rowmiss()
robs() rownonmiss()
rsd() rowsd()
rsum() rowtotal()
sum() total()
The new names are more consistent. Old names continue to work but are not documented.
clear
set obs 5
generate x = _n if _n != 3
* Create variable containing the running sum of x
generate runsum = sum(x)
* Create variable containing a constant equal to the overall sum of x
egen totalsum = total(x)
* List the results
list
Copyright © 2003-2013 www.wpsshop.cn 版权所有,并保留所有权利。