Statistics 宏上的Stata行为,不同的输出

Statistics 宏上的Stata行为,不同的输出,statistics,stata,Statistics,Stata,我在stata的宏中创建了一个手动列表,类似于 global list1 "a b c d" `"This is a string with `"another quoted string"' inside it"' 我后来用类似的东西重复了一遍 foreach name in $list1 { action } 我试图将其更改为DB驱动的列表,因为该列表变得越来越大并且变化很快,我使用以下命令创建了一个新的$list1 odbc load listitems=items, exec("S

我在stata的宏中创建了一个手动列表,类似于

global list1 "a b c d"
`"This is a string with `"another quoted string"' inside it"'
我后来用类似的东西重复了一遍

foreach name in $list1 {
action
}
我试图将其更改为DB驱动的列表,因为该列表变得越来越大并且变化很快,我使用以下命令创建了一个新的$list1

odbc load listitems=items, exec("SELECT items  from my_table")  
levelsof listitems
global list1=r(levels)
每个列表上的项目都是相同的,但是这个列表似乎不同,当我有太多的项目时,它会在for循环中出现错误

{ required
r(100);
另外,当我只运行levelsofListItems时,我会得到输出

`"a"' `"b"' `"c"' `"d"' 
它看起来和其他宏有点不同

我被困在这里面有一段时间了。同样,只有当项目数量变大(超过15个)时,它才会失败,我们非常感谢您的帮助。

解决方案1:

levelsof listitems, clean local(list1)
foreach name of local list1 {
    ...action with `name'...
}
解决方案2:

levelsof listitems, clean
global list1 `r(levels)'
foreach name of global list1 {
    ...action with `name'...
}

说明:

你打字的时候

foreach name in $list1 {
然后,在Stata看到$list1中的任何内容之前,都会被内联替换。如果全局宏列表1包含很长的内容列表,则Stata将看到

foreach name in a b c d e .... very long list of things here ... {
更有效的方法是告诉Stata您在全局或局部宏中有一个事物列表,并且希望循环这些事物。您不必在命令行上展开它们。那是什么

foreach name of local list1 {

是给你的。您可以在-help-foreach-中阅读foreach的其他功能

而且,您最初编写了

levelsof listitems
global list1=r(levels)
你注意到你看到了

`"a"' `"b"' `"c"' ...
结果,。这些是Stata所称的“复合引号”字符串。复合引用字符串可以有效地嵌套引用的内容。所以,你可以有这样的东西

global list1 "a b c d"
`"This is a string with `"another quoted string"' inside it"'
你说你不需要它,所以你可以使用levelsof的“clean”选项来不引用结果。(有关此选项的详细信息,请参见-help levelsof-)此外,您还将levelsof的返回结果(在r(levels)中)分配给了一个全局宏。事实证明-levelsof-实际上有一个名为-local()的选项,您可以在其中指定本地(而不是全局)宏的名称,以直接将结果放入。因此,您只需键入

levelsof listitems, clean local(list1)
省略复合引号并将结果直接放入名为list1的本地宏中

最后,如果出于某种原因不想使用local()选项,并且希望坚持将列表放入全局宏中,那么应该编写代码

global list1 `r(levels)'
而不是

global list1=r(levels)
区别在于后者将r(levels)视为一个函数,并通过Stata的字符串表达式解析器运行它。在Stata中,字符串(字符串,而不是包含字符串的宏)限制为244个字符。另一方面,包含字符串的宏可以包含数千个字符。所以,如果r(levels)中有超过244个字符,那么

global list1=r(levels)
将最终截断存储在列表1中的244个字符的结果

当你改为编码时

global list1 `r(levels)'
然后,在执行命令之前,将r(级别)的内容展开。所以,斯塔塔看到了

global list1 a b c d e ... very long list ... x y z

宏名称(列表1)之后的所有内容都会复制到该宏名称中,无论它有多长。

Alan。对Stata宏的复杂性的奇妙解释。谢谢。@Alan(+1)很好的解释!