3

我有带有 ID 的数据,这些数据可能存在也可能不存在所有值。我只想删除没有数据的观察;如果有一个值的观察值,我想保留它们。例如,如果我的数据集是:

ID val1 val2 val3 val4
1 23 . 24 75
2 . . . .
3 45 45 70 9

我只想删除 ID 2,因为它是唯一一个没有数据的——只是一个 ID。

我尝试过 Statalist 和 Google,但找不到任何相关内容。

4

3 回答 3

7

只要字符串为空,这也适用于字符串:

ds id*, not
egen num_nonmiss = rownonmiss(`r(varlist)'), strok
drop if num_nonmiss == 0

这将获取不是 id 的变量列表,并删除任何仅具有 id 的观察值。

于 2014-08-06T17:07:52.940 回答
4

Brian Albert Monroe 非常正确,任何使用dropmiss(SJ) 的人都需要先安装它。由于人们对解决此问题的不同方法感兴趣,我将添加另一种方法。

 foreach v of var val* { 
     qui count if missing(`v') 
     if r(N) == _N local todrop `todrop' `v' 
 }
 if "`todrop'" != "" drop `todrop' 

虽然它应该是 Brian 的回答下的评论,但我将在此处添加评论,因为 (a) 这种格式更适合显示代码 (b) 评论来自我上面的代码。我同意这unab是一个有用的命令,并且经常在公开场合称赞它。然而,在这里,这是不必要的,因为布赖恩的循环可以很容易地开始像

 foreach v of var * { 

2015 年 9 月更新:有关信息,请参见http://www.statalist.org/forums/forum/general-stata-discussion/general/1308777-missings-now-available-from-ssc-new-program-for-managing-missings on missings,两者的作者都认为是对 的改进dropmissdrop当且仅当所有值都丢失时,观察的语法是missings dropobs.

于 2014-08-08T11:42:01.060 回答
0

这只是另一种方法,它可以帮助您发现本地宏的灵活性,而无需为 Stata 安装任何额外的东西。我很少看到使用本地存储命令或逻辑条件的代码,尽管它通常非常有用。

    // Loop through all variables to build a useful local
    foreach vname of varlist _all {    

            // We don't want to include ID in our drop condition, so don't execute the remaining code if our loop is currently on ID
            if "`vname'" == "ID" continue  

            // This local stores all the variable names except 'ID' and a logical condition that checks if it is missing
            local dropper "`dropper' `vname' ==. &"     
    }

    // Let's see all the observations which have missing data for all variables except for ID
    // The '1==1' bit is a condition to deal with the last '&' in the `dropper' local, it is of course true.

    list if `dropper' 1==1

    // Now let's drop those variables
    drop if `dropper' 1==1

    // Now check they're all gone
    list if `dropper' 1==1

    // They are.

现在dropmiss下载并安装后可能会很方便,但是如果您正在编写一个供其他人使用的 do 文件,除非他们也已dropmiss安装,否则您的代码将无法在他们的机器上运行。

使用这种方法,如果您删除注释行和两个不必要的列表命令,这是一个相当稀疏的 5 行代码,它将在 Stata 开箱即用的情况下运行。

于 2014-08-07T22:31:07.453 回答