Warning: file_get_contents(/data/phpspider/zhask/data//catemap/9/spring-boot/5.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
stata语法中的可变长度字符串参数_Stata - Fatal编程技术网

stata语法中的可变长度字符串参数

stata语法中的可变长度字符串参数,stata,Stata,为了清理数据,我正在编写一个函数,该函数接受变量列表,并用空字符串替换字符串列表。虽然我有代码来解决这个问题,但我想学习如何使用长度可变的字符串列表作为参数 为了理解这个简单的版本,下面将用一个空字符串替换myval1和myval2中的任何“X”,称为: replace_string_with_empty myval1 myval2, code("X") 代码是 capture program drop replace_string_with_empty program replace_

为了清理数据,我正在编写一个函数,该函数接受变量列表,并用空字符串替换字符串列表。虽然我有代码来解决这个问题,但我想学习如何使用长度可变的字符串列表作为参数

为了理解这个简单的版本,下面将用一个空字符串替换myval1和myval2中的任何“X”,称为:

 replace_string_with_empty myval1 myval2, code("X")
代码是

 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
但是如果我有几个代码呢?忘记了可能有更干净的方法可以做到这一点,我想称之为

 replace_string_with_empty myval1 myval2, codes("X" "NONE")
但是我不能确定syntax命令中的类型,等等。例如,以下命令不起作用

 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

有什么想法吗?(同样,我确信有更好的方法来解决这个确切的问题,但我想弄清楚如何以这种方式将
语法
用于其他任务。

这里是一个简单的方法示例。
asis
选项将不使用引号,但我们在引用st时需要使用复合引号。)要重新编码为空的环:

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

下面是一个简单的例子,说明了一种方法。
asis
选项将不使用引号,但在引用要重新编码为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") 

你写strec有什么原因吗?我不知道。谢谢你,我现在将在我的代码中使用它。也就是说,我的主要问题是如何处理这些类型的参数(而不是解决这个确切的问题)。你写strec有什么原因吗?我不知道。谢谢,我现在将在我的代码中使用它。也就是说,我的主要问题是如何处理这些争论(而不是解决这个问题)@jlperla如果这有帮助,请选择这个作为答案。是的,只是测试它。效果很好。再次感谢。@jlperla如果这有帮助,请选择这个作为答案。是的,只是测试它。效果很好。再次感谢。