To cleanup data, I am writing a function which takes a list of variables, and replaces a list of strings with empty strings. While I have code to solve the problem, I want to learn how to use a variable length list of strings as an argument.
To get a sense of the simple version, the following would replace any "X" in myval1 and myval2 with an empty string, and is called like:
replace_string_with_empty myval1 myval2, code("X")
The code is,
capture program drop replace_string_with_empty
program replace_string_with_empty
syntax varlist(min=1), Code(string)
foreach var in `varlist' {
replace `var' = "" if `var' == "`code'"
}
end
But what if I have several codes? Forgetting that there may be cleaner ways to do this, I would like to call this as things like
replace_string_with_empty myval1 myval2, codes("X" "NONE")
But I can't figure out the type in the syntax command, etc. For example, the following does not work
capture program drop replace_string_with_empty
program replace_string_with_empty
syntax varlist(min=1), Codes(namelist)
foreach var in `varlist' {
foreach code in `codes' {
replace `var' = "" if `var' == "`code'"
}
}
end
Any ideas? (again, I am sure there are better ways to solve this exact problem, but I want to figure out how to use the syntax
in this way for other tasks as well.
strrec
? – dimitriy