Generating a new variable using conditional statements

自闭症网瘾萝莉.ら 提交于 2020-01-30 12:21:06

问题


Given the following dataset and commands:

sysuse auto, clear

generate x = .
replace x = 5 if price == 4099
replace x = 5 if price == 4749

I want to generate a new variable x that is equal to 5 if price belongs to a list of values.

The following command generates no new values of x and is incorrect:

replace x = 5 if price == 4099 & price == 4749

I need a simpler one-line method that does not involve replacing x the way I did it in the code above, which works, but is tedious and inelegant.


回答1:


You need to use 'or' (|) instead of 'and' (&):

sysuse auto, clear

generate x = .
replace x = 5 if price == 4099
replace x = 5 if price == 4749

generate y = 5 if price == 4099 | price == 4749

Alternatively you can use the inlist() function:

generate z = 5 if inlist(price, 4099, 4749)

Results:

list price x y z in 1 / 5

     +-------------------+
     | price   x   y   z |
     |-------------------|
  1. | 4,099   5   5   5 |
  2. | 4,749   5   5   5 |
  3. | 3,799   .   .   . |
  4. | 4,816   .   .   . |
  5. | 7,827   .   .   . |
     +-------------------+


来源:https://stackoverflow.com/questions/57788794/generating-a-new-variable-using-conditional-statements

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