How to Replace Specific Values a Variable Takes Through a Loop in Stata

I am looking to replace a list of variables that take string value "NR" with missing. The command is replace. However, the foreach loop for the varlist does not seem to be working. After running and reviewing the dataset, the values are still "NR" instead of "."

Code:

local vars fpl_100_150 fpl_150_200 fpl_200_250 

foreach var of local vars {
    replace 'var' = "." if 'var' == "NR"
}
1

1 Answer

Two things.

First, the error in your code is that you reference the local var created in foreach var of local vars { as 'var' and not `var'. So the fix to the error you are getting would be this:

local vars fpl_100_150 fpl_150_200 fpl_200_250 

foreach var of local vars {
    replace `var' = "." if `var' == "NR"
}

Additionally, the convention for missing string values in Stata is the empty string "". . is the convention to represent missing numeric values. This becomes relevant when Stata commands test a variable such as with missing(fpl_100_150 ). That syntax is commonly used inside other commands: the function missing() classifies "." as not missing but "" as missing. Therefore I suggest that you change the line inside the loop to replace `var' = "" if `var' == "NR".

1

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge that you have read and understand our privacy policy and code of conduct.

Elena Rostova

Elena Rostova

Lead Health, Wellness & Medical Journalist

Elena Rostova holds a Master's degree in Public Health Journalism. She covers groundbreaking medical research, holistic wellness trends, mental health awareness, and nutritional science.

Share this article
Twitter Facebook Pinterest