我之前从未使用过Stata,对它的了解非常少。我一直试图根据year
,country1
,country2
折叠双边信息数据集,并采取所有其他信息的方式。在R中,我试着跑:
aggregate(dataset,by=list(dataset$year,dataset$country1,dataset$country2),FUN=mean,na.rm=TRUE)
数据集太大,我的计算机的RAM无法处理我在R中的崩溃(另一个我无法解决的问题),当同事试图运行代码时,其他数据没有显示为手段(在某些情况下,只选择了特定二元年份的一行数据;在其他情况下,我甚至不确定发生了什么。较小的数据集子集显示了正确的结果。
由于R中存在问题,我想尝试在Stata中执行此操作,但我之前尝试使用
collapse (mean) <every variable I wanted a ``mean'' of, or otherwise wanted to remove from the dataset>, by(year country1 country2)
Stata不知道如何处理字符串。我对Stata的了解很少,我无法弄清楚如何解决这个问题。有人可以提供我需要在大量变量上使用collapse
命令的代码,其中许多是字符串(对于字符串,我想要NA
返回)?
答案 0 :(得分:2)
您可以使用ds
自动选择数字变量。 ds
是一个官方指挥。 findname
( Stata Journal )是ds
的用户编写后继者,具有更多功能(事实)和更友好的语法(作者的意见,尽管同一作者是ds
)的最后一位作者。
. sysuse auto
(1978 Automobile Data)
. ds, has(type numeric)
price rep78 trunk length displacement foreign
mpg headroom weight turn gear_ratio
. findname, type(numeric)
price rep78 trunk length displacement foreign
mpg headroom weight turn gear_ratio
在这两种情况下,您都会发现r(varlist)
中返回了数字变量的名称:
. di "`r(varlist)'"
price mpg rep78 headroom trunk weight length turn displacement gear_ratio foreign
以便将其提供给collapse
. collapse `r(varlist)', by(year country1 country2)
一般来说,阅读collapse
的帮助和手动条目是无可替代的。
答案 1 :(得分:1)
如果您尝试计算平均值的字符串变量是被视为字符串的数字,例如“1”,“2”等,然后您可以使用real()
或destring
将变量转换为数字类型。字符串变量不是这种形式,例如“鳄鱼”,“蜥蜴”,“蛇”等等,如果它们不包含在collapse
中,将被删除。
示例:
clear all
set more off
* some example data
input ///
str4 numstr num str11 reptiles
"234" 234 "alligator"
"2135" 2135 "lizard"
"324" 324 "snake"
end
list
* create numeric variable from string
destring(numstr), gen(num2)
* the collapse
collapse (mean) num num2
list