Keeping all the records for specific IDs

馋奶兔 提交于 2019-12-11 17:06:38

问题


I have the following dataset:

clear

input id code cost
1 15342 18
2 15366 12
1 16786 32
2 15342 12
3 12345 45
4 23453 345
1 34234 23
2 22223 12
4 22342 64
3 23452 23
1 23432 22
end

I want to get the output below:

id    code   cost  
 1   15342     18  
 2   15366     12  
 1   16786     32  
 2   15342     12  
 1   34234     23  
 2   22223     12  
 1   23432     22  

I tried to use this command but it did not work:

keep if id = (1|2)

How can I keep all the records for specific IDs?


回答1:


The following works for me:

keep if id == 1 | id == 2

Alternatively, you can use the inlist() function:

keep if inlist(id, 1, 2)

In this particular case (and more generally when the wanted IDs are consecutive), the inrange() function will also work:

keep if inrange(id, 1, 2)

Results in all cases:

list, separator(0)

     +-------------------+
     | id    code   cost |
     |-------------------|
  1. |  1   15342     18 |
  2. |  2   15366     12 |
  3. |  1   16786     32 |
  4. |  2   15342     12 |
  5. |  1   34234     23 |
  6. |  2   22223     12 |
  7. |  1   23432     22 |
     +-------------------+


来源:https://stackoverflow.com/questions/57860764/keeping-all-the-records-for-specific-ids

标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!