当前位置:   article > 正文

Stata中一些令人困扰的易错函数——sum()和total()_stata total函数

stata total函数
  • 问题:Stata中有两个求和函数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
  • 1
  • 2
  • 3
  • 4
  • 5
  • 6
  • 7
  • 8
  • 9
  • 10
  • 11
  • 12
  • 13
  • 14
  • 15
  • 16
  • 17
  • 18
  • 19
  • 20
  • 21
  • 22
  • 23
  • 24
  • 25
原因
  • help sum()
    sum(x): the running sum of x, treating missing values as zero.For example, following the command generate y=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()
  • 1
  • 2
  • 3
  • 4
  • 5
  • 6
  • 7
  • 8
  • 9
  • 10
  • 11
  • 12
  • 13
  • 14

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
  • 1
  • 2
  • 3
  • 4
  • 5
  • 6
  • 7
  • 8
  • 9
  • 10
  • 11
  • 12
声明:本文内容由网友自发贡献,不代表【wpsshop博客】立场,版权归原作者所有,本站不承担相应法律责任。如您发现有侵权的内容,请联系我们。转载请注明出处:https://www.wpsshop.cn/w/Monodyee/article/detail/514455
推荐阅读
相关标签
  

闽ICP备14008679号