Maybe this example helps:
clear all
set more off
/*
load two example MS Excel files with var names only and accumulate var names in a local.
files are named varfile.xls and varfile2.xls
*/
foreach i in "" "2" {
import excel "/home/roberto/Desktop/stata_tests/varfile`i'.xls", firstrow clear
* get var names
quietly ds
* save var names in local
local myvars `myvars' `r(varlist)'
}
* load database that contains vars and values
sysuse auto, clear
* do pca
pca `myvars'
/*
varfile.xls contains variables "weight" and "price"
varfile2.xls contains variables "mpg" and "length"
*/
ds
does the trick here because it saves the names of the variables picked up in the MS Excel sheet and stores the result in r(varlist)
. See help ds
and help saved results
(or help stored results
). Afterwards, we load a "complete" database and use the stored variable names with pca
.
The MS Excel files look like this:
This, I think, answers the specific question you pose.
Edit
Looking closer at your code, I'm not sure the problem is related to matching variable names in the complete database, but rather some problem with the way you set up preserve
and restore
. Instead of using that set of commands, try simply loading the complete database when you need it (with use
).
What do you have before the preserve
? Where does your error appear? Please post more code. A reproducible example would help.
Edit 2
My conjecture now is that you have nothing before the preserve
, so when you restore
, you're just setting the slate clean; you are restoring a blank database. Therefore, trying pca <somevar>
gives you:
no variables defined
r(111);
preserve
preserves the data as it is just before the command is issued.