I am trying to calculate a partial correlations for many variables with regard to one variable while only considering nonmissing observations in terms of both the i and the j and also output all the partial correlations to excel.
This code is close I think, but not working. There is a problem in the loop. (I am not great at loops.) The error is "too few variables" r(102).
One can assume the "control" variable is never missing, but sometimes observations in the "varlist" variables are missing in a random way. I know the "webuse auto" dataset doesn't have missing obs, but please pretend that it does.
Thanks in advance.
This code is close I think, but not working. There is a problem in the loop. (I am not great at loops.) The error is "too few variables" r(102).
One can assume the "control" variable is never missing, but sometimes observations in the "varlist" variables are missing in a random way. I know the "webuse auto" dataset doesn't have missing obs, but please pretend that it does.
Code:
webuse auto, clear local varlist mpg trunk weight length turn // main variables local control price // variable to partial out local nvars : word count `varlist' matrix pmat = J(`nvars', `nvars', .) forvalues i = 1/`nvars' { local vi : word `i' of `varlist' forvalues j = `i'/`nvars' { local vj : word `j' of `varlist' preserve quietly keep if !missing(`vi', `vj', `control') * Run partial correlation quietly pcorr `vi' `vj' `control' * Extract correlation and store in matrix matrix temp = r(Rho) local val = temp[1,2] matrix pmat[`i', `j'] = `val' matrix pmat[`j', `i'] = `val' restore } } matrix rownames pmat = `varlist' matrix colnames pmat = `varlist' putexcel set partial_corr_output.xlsx, replace putexcel A1 = matrix(pmat), names
Comment