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

文章探讨了Stata中求和函数sum()和total()的区别。sum()计算运行总和,将缺失值视为零,而total()生成整体总和,只能在egen命令中使用。尽管在egen中sum()和total()结果相同,但在gen中它们有不同的行为。Stata已将某些egen函数重命名以提高一致性,旧名称仍可工作但未被文档记录。文章通过示例代码解释了这两个函数的用法和潜在陷阱。
摘要由CSDN通过智能技术生成
  • 问题: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
原因
  • 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()

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
  • 0
    点赞
  • 2
    收藏
    觉得还不错? 一键收藏
  • 2
    评论
评论 2
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值