Hello,
I'm new to Stata (and new to this forum ) and I'm trying to do something probably quite basic but it doesn't want to work.
Basically, I have 2 datasets, firstfile_new (my main dataset) and secondfile (that gives me additionnal information on my variables).

I would like to rename the variables of the firstfile_new based on an information that I can find on the secondfile. More precisely, I would like to add to the variable names the first 2 characters of their type, so having "2 first characters of type" + "." + "variable name", type being a variable of the secondfile.
Remark : most of the variables have 8 characters in their names and start all with gfdd. Only 4 are different and I wanted to thus start with all of those that start with gfdd (and change the other without a loop or anything).

For example, the variable gfddai01 is of the type access (information that I have on the secondfile), and I want to rename it as "AC.gfddai01".

I have started by creating a new variable on the secondfile that consists in the old variables names transformed the want I want it.

Code:
use secondfile3.dta, clear

*Create this new variable
replace Type = upper(Type)
generate ty_var = substr(Type,1,2) + "." + Old_Variable
replace Type = lower(Type)

*Replace for the 4 last variables (otherwise other and other economic variables have the same starting name)
replace Variable = "OE.ny_gdp_mktp_cd" if Variable == "OT.ny_gdp_mktp_cd"
replace Variable = "OE.ny_gdp_pcap_kd" if Variable == "OT.ny_gdp_pcap_kd"
replace Variable = "OE.ny_gnp_mktp_cd" if Variable == "OT.ny_gnp_mktp_cd"
replace Variable = "OE.sp_pop_totl" if Variable == "OT.sp_pop_totl"

*Reorder 
order ty_var, b(Label)

*Rename new_variable
rename ty_var Variable

*save secondfile
save secondfile4
Then, I do :

Code:
quietly levelsof Variable, local(Var_new_name)
foreach y in local Var_new_name {
    local pref = substr("`y'",4,7)
    if "`pref'" == "gfdd" {
        local teest = "`y'"
    } 
}

*use firstfile
use firstfile_new.dta, clear

foreach x of local teest  {
    local old_var = substr("`x'",4,11)
    quietly ds, has(varlabel *"`old_var'")
    local varlist `r(varlist)'
    
    foreach var of local varlist {
    rename `var' `"`x'"'
    }
}
it doesn't give me error message, but it doesn't change my variable names. So I guess the problem comes from macros (that I still have a hard time using).

Could you help please?

Thanks
Saloua