【问题标题】:Including a variable local macro inside a loop在循环中包含变量局部宏
【发布时间】:2013-06-25 16:57:15
【问题描述】:

使用forvalues 循环,我正在合并一个包含 400 个单独数据集的列表。

这些数据集可以是 10 个不同的值之一(由数据集中的变量定义):根据数据集,我会 merge 使用不同的数据集。例如,如果玩家 90 是类型 9,我希望与 Type_9.dta 合并,而不是 Type_8Type_7

我想要的是这样的:

forvalues x = 1/400 {
    use "player_`x'.dta"

    * some way to turn the value of player type into a local macro l *

    merge 1:1 using "type_`l'.dta"
}

如何将变量类型转换为通过循环为每种类型更改的宏?

【问题讨论】:

  • 下面的答案有帮助吗?

标签: for-loop stata local stata-macros


【解决方案1】:

您的数据结构和最终目标对我来说不是很清楚,因此可能有更有效的方法来做到这一点。

如果 player_type 在每个 player_* 数据集中没有变化,您可以使用 levelsof。它的特点是如果 player_type 因某种原因(例如数据输入错误)而变化,则循环将出错。

forvalues x = 1/400 { 
   use "player_`x'.dta"
   levelsof player_type, local(l)
   merge 1:1 **some_id_var** using "type_`l'.dta" 
}

【讨论】:

  • 这对我来说也不清楚:例如,如果您已经有merged 一个数据集,那么如何阻止再次执行该操作?但是如果player_type 是常量,使用player_type[1] 的值就足够了,所以不需要启动levelsof
  • 我使用了levelsof,因为如果player_type 实际上不是常量,则循环将中断。
  • 很好;我现在看到了。最好在修改答案时说明这一点?
猜你喜欢
  • 2014-11-21
  • 1970-01-01
  • 2014-02-07
  • 2017-07-11
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多