Dear Statalist community

I´ve encountered a wierd situation today: failing to define a new scalar. Below is my code:

Code:
forvalues i = 2002(3)2014 {
    foreach k in real_estate house_debt other_debt ownership {
        forvalues j = 1/4 {
            *Create the sum of replicate weights
            cd $datainput/`i'
            use databol1, clear
            sum facine3 if percriq == `j'
            scalar weight_g`j' = r(sum)
            
            *Using combined imputation dataset to calculate mean of var of interest for each wealth group
            use comb_imp, clear
            mi import flong, m(mdataset) id(h_`i') 
            mi estimate, esampvaryok post: reg `k' [pweight=facine3] if percriq == `j'
            mat b = e(b)
            scalar `k'_g`j' = b[1,1]
            
            *For ownership, our goal is to calculate ownership rate
            *For other variables, calculate the weighted sum
            if `k' == ownership {
                scalar w_`k'_g`j' = `k'_g`j'
                else {
                    scalar w_`k'_g`j' = weight_g`j' * `k'_g`j'
                }
            }
            
            *Copy and paste the result, which is a scalar, to a new dataset
            cd $datatable\by_group
            use microagg_group, clear
            replace `k' = w_`k'_g`j' if year == `i' & group == `j'
            save microagg_group, replace
        }
    }
}
So the idea is to calculate weighted sum of vars of interest using a dataset comp_imp, which is the combination of imputed datasets. The codes run well until the step when I attempt to copy the computed result, which is stored in scalar w_`k'_g`j' (w_real_estate_g1 for example). It stops at the line
Code:
replace `k' = w_`k'_g`j' if year == `i' & group == `j'
with error code r(111), w_real_estate_g1 not found

I checked scalar list by using scalar dir, it turns out scalar weight_g1 and scalar real_estate_g1 have been defined, which means that something wrong happened in the if clause. I then changed the structure to single command one:
Code:
if "`k'" == "ownership" scalar w_`k'_g`j' = `k'_g`j'
            else scalar w_`k'_g`j' = weight_g`j' * `k'_g`j'
Then it finally works. The story seems to tell me that the problem lies in the structure of if clause.

What´s even more wierd, I succeeded at producing the result I want using the same code one hour ago (with trifling modification). The if structure was exactly the same in that code, and the names for scalars are the same as well.

Could someone provide some explanations? I´d appreciate your help!