给定一些变量可能不存在时,如何保存它们的列表? [英] How to keep a list of variables given some of them may not exist?

查看:111
本文介绍了给定一些变量可能不存在时,如何保存它们的列表?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有100个 dta 文件。我有一个变量列表,需要保留并动态保存临时副本。某些 dta 中可能存在也可能不存在某些变量。

I have 100 dta files. I have a list of variables that I need to keep and save temporary copies on the fly. Some variables may or may not exist in a certain dta.

我需要Stata保留 dta 中存在的所有变量,并忽略不存在的变量。

I need Stata to keep all variables that exist in a dta and ignore those that do not exist.

下面的代码语法错误,但是它可以作为一个很好的伪代码,使您对应该执行的操作有一个大致的了解:

The following code has wrong syntax, but it could serve as a good pseudo code to give one a general idea of what should be done:

forval j = 1/100 {
    use data`j'
    local myVarList =""

    foreach i of varlist  var1 var2 var3 var4 var5 var6 var7 var8  {
        capture sum `i'
        if _rc = 0 {
            `myVarList' = `myVarList'" "`i'
        }
    }

    keep `myVarList'
    save temporaryData`j'
}

有什么办法吗?

推荐答案

问题很多您的代码。这是进行内循环的一种方法。

There are many issues with your code. Here's one way to do the inner loop.

/* one fake dataset */
set obs 5
gen var1 = 1
gen var2 = 2
gen var3 = "c"
gen z    = 35

ds

/* keep part */
local masterlist "var1 var2"
local keeplist = ""

foreach i of local masterlist  {
    capture confirm variable `i'
        if !_rc {
            local keeplist "`keeplist' `i'"
        }
}

keep `keeplist'

关键部分是您不能遍历varlist phantomvar的i 将检查是否存在并出错。同样,将本地名称加上特殊引号会对其进行评估,但您正在尝试重新定义。您可能会发现上的设置跟踪在调试中很有用。

The key part is that you can't foreach i of varlist phantomvar, since Stata will check the existence and error out. Similarly, putting the local name in special quotes will evaluate it, but you're trying to redefine. You may find set trace on a useful feature in debugging.

这是更好的代码:

unab allvars: _all
local masterlist "var1 var2 phantomvar"
local keeplist: list allvars & masterlist
keep `keeplist'

这篇关于给定一些变量可能不存在时,如何保存它们的列表?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆