Stata Tips 102:如何生成30个连续变量的交互项
(2014-01-16 15:13:23)分类: 经济学家们 |
1.简单的方法(转)
Tips 9:genicv产生交叉项
【问题】
有时候,想生成很多交叉项,但是又不愿意一个一个写。
有时候,想看一个交叉项,但是又不愿意生成。
【方法】
genicv可以一键生成很多交叉项
##可以直接表示交叉项。
【例子】
ssc install genicv
sysuse auto,clear
genicv length weight foreign
reg price length weight length_weight
*如果不愿意生成,直接用
reg price c.length##c.weight
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' {
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)
推荐一位 Stata 大神
政治学的
Boston College Department of
Economics
Statistical Software
Components