新浪博客

Stata Tips 102:如何生成30个连续变量的交互项

2014-01-16 15:13阅读:
1.简单的方法(转)

Tips 9:genicv产生交叉项


【问题】
有时候,想生成很多交叉项,但是又不愿意一个一个写。
有时候,想看一个交叉项,但是又不愿意生成。
【方法】
genicv可以一键生成很多交叉项
##可以直接表示交叉项。
【例子】
ssc install genicv
sysuse auto,clear
genicv length weight foreign \\\会生成4个交叉项,所以可能情况,并且有label
reg price length weight length_weight
*如果不愿意生成,直接用
reg price c.length##c.weight \\\和上面回归一样一样的
原链接:http://blog.sina.cn/dpool/blog/s/blog_629bb75801011qg6.html?vt=4
2.网上的方法
*Leaving aside whether this is wise, I'd do something like this:
clear
set obs 100
forv i=1/30 {
gen var`i'=_n
}
unab vars : var1-var30
di `vars'
local nvar : word count `vars'
di `nvar'
forval i = 1/`nvar' {
forval j = 1/`=`i'-1' { //循环中暂元的计算要加上“=”
local x : word `i' of `vars'
local y : word `j' of `vars'
generate `x'X`y' = `x' * `y'
}
}
/*
This puts the variable list into local macro `vars', then grabs the variables sequentially from the list.
The inner loop (y) only goes up to the variable prior to the current outer loop (x) variable,
which means we create only one version of each interaction and avoid creating the squares of each variable as well.
Or, in Stata 11, you can specify all the interactions with factor varlists, without creating any interaction variables at all.
For example, to regress variable myvar on all the interactions: regress myvar c.(var1-var30)#c.(var1-var30)
regress myvar c.(var1-var30)#c.(var1-var30)


原始链接:http://www.stata.com/statalist/archive/2009-09/msg00449.html
推荐一位 Stata 大神 政治学的
个人主页:http://faculty.virginia.edu/nwinter/progs/
Boston College Department of Economics
Statistical Software Components
链接:http://ideas.repec.org/s/boc/bocode.html


我的更多文章

下载客户端阅读体验更佳

APP专享