0
votes

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.

1
Is there a reason you are re-writing strrec?dimitriy
I didn't know about that. Thank you, I will use it in my code now. That said, my main question is about how to deal with those sorts of arguments (rather than solving this exact problem).jlperla

1 Answers

2
votes

Here's a simple example of one approach to this. The asis option will leave the quotes alone, but we will then need to use compound quotes when referring to the strings that are to be recoded to null:

capture program drop replace_string_with_empty    
program replace_string_with_empty
syntax varlist(min=1 string), Codes(string asis)
tokenize `"`codes'"'
while "`1'" != "" {
    foreach var of varlist `varlist' {
        replace `var' = "" if `var'==`"`1'"'
    }
    macro shift
}
end

sysuse auto, clear
clonevar make2=make
replace_string_with_empty make*, codes("AMC Concord" "AMC Spirit" "Audi 5000")