program define regkv
version 10
syntax [varlist] [if] [in] [fweight  aweight  pweight  iweight] [,cluster *]

* messungen, die nicht in die analyse eingehen vor erstellung der kontextvariablen ausschließen
qui generate usempf=1
qui foreach i in `varlist' {
replace usempf=0 if `i'==.
}

tokenize `varlist'
local first `1'
macro shift
local rest `*'
	_xt, i(`i')
local ivar "`r(ivar)'"
qui foreach i in `rest' {
egen kv_`i' = mean (`i') if usempf==1, by (`ivar')
}
_rmcoll `rest' kv_*
local xvars `r(varlist)'
reg `first' `xvars' `if' `in' [`weight' `exp'], `options'
drop kv_*  usempf
end