如何标记扩展宏(本地 :dir )?
How to tokenize a extended macro (local :dir )?
我知道我的标题令人困惑,因为 tokenize
命令被指定为一个字符串。
我有很多文件夹,其中包含大量、分离的 ill-named Excel 文件(其中大部分是从网站上抓取的)。手动 select 它们很不方便,所以我需要依靠 Stata 扩展宏函数 local :dir
来阅读它们。
我的代码如下所示:
foreach file of local filelist {
import excel "`file'", clear
sxpose, clear
save "`file'.dta", replace
}
这样的代码会生成很多新的dta
文件,因此目录中充满了这些文件。我更喜欢为第一个 xlsx
文件创建一个新的数据文件,然后在 foreach
循环中为它创建 append
其他文件。所以本质上,循环内有一个 if-else
。
我们需要一个刚刚创建的宏 filelist
的索引,这样我们就可以这样写:
token `filelist' // filelist is created in the former code
if "`i'" == `1' {
import excel "`file'",clear
}
else {
append using `i',clear
}
我知道我的代码效率低下 error-prone:表达式 token 'filelist'
的语法也不正确(假定 filelist
不是字符串)。但是,我仍然想弄清楚我的伪代码背后的基本结构。
我怎样才能更正我的代码并使其正常工作?
非常欢迎另一种更有效的方法。
需要注意的各种技术 spring,其中 none 需要标记化。
local count = 1
foreach file of local filelist {
import excel "`file'",clear
sxpose, clear
if `count' == 1 save alldata
else append using alldata
local ++count
}
local allothers "*"
foreach file of local filelist {
import excel "`file'",clear
sxpose, clear
`firstonly' save alldata
`allothers' append using alldata
local firstonly "*"
local allothers
}
在第二个块中,重点是前缀为 *
的行被视为注释,因此 *
之前的任何命令都将被忽略 ("commented out")。 append
语句在循环中第一次被注释掉,并且 save
语句前面有一个未定义的本地宏,它的计算结果为空字符串,所以它是 not 忽略。
第一次循环后,append
上的注释被删除,但放在 save
上。
我认为这些方法中的任何一种都没有比您想象的更有效(工作速度更快、使用更少的内存、更短,或者 "efficient" 对您意味着什么)。代码显然假定您已正确设置文件列表。
我知道我的标题令人困惑,因为 tokenize
命令被指定为一个字符串。
我有很多文件夹,其中包含大量、分离的 ill-named Excel 文件(其中大部分是从网站上抓取的)。手动 select 它们很不方便,所以我需要依靠 Stata 扩展宏函数 local :dir
来阅读它们。
我的代码如下所示:
foreach file of local filelist {
import excel "`file'", clear
sxpose, clear
save "`file'.dta", replace
}
这样的代码会生成很多新的dta
文件,因此目录中充满了这些文件。我更喜欢为第一个 xlsx
文件创建一个新的数据文件,然后在 foreach
循环中为它创建 append
其他文件。所以本质上,循环内有一个 if-else
。
我们需要一个刚刚创建的宏 filelist
的索引,这样我们就可以这样写:
token `filelist' // filelist is created in the former code
if "`i'" == `1' {
import excel "`file'",clear
}
else {
append using `i',clear
}
我知道我的代码效率低下 error-prone:表达式 token 'filelist'
的语法也不正确(假定 filelist
不是字符串)。但是,我仍然想弄清楚我的伪代码背后的基本结构。
我怎样才能更正我的代码并使其正常工作?
非常欢迎另一种更有效的方法。
需要注意的各种技术 spring,其中 none 需要标记化。
local count = 1
foreach file of local filelist {
import excel "`file'",clear
sxpose, clear
if `count' == 1 save alldata
else append using alldata
local ++count
}
local allothers "*"
foreach file of local filelist {
import excel "`file'",clear
sxpose, clear
`firstonly' save alldata
`allothers' append using alldata
local firstonly "*"
local allothers
}
在第二个块中,重点是前缀为 *
的行被视为注释,因此 *
之前的任何命令都将被忽略 ("commented out")。 append
语句在循环中第一次被注释掉,并且 save
语句前面有一个未定义的本地宏,它的计算结果为空字符串,所以它是 not 忽略。
第一次循环后,append
上的注释被删除,但放在 save
上。
我认为这些方法中的任何一种都没有比您想象的更有效(工作速度更快、使用更少的内存、更短,或者 "efficient" 对您意味着什么)。代码显然假定您已正确设置文件列表。