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...
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 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".