Generating a new variable using conditional statements

前端 未结 1 1857
花落未央
花落未央 2021-01-28 09:56

Given the following dataset and commands:

sysuse auto, clear

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

I wa

相关标签:
1条回答
  • 2021-01-28 10:04

    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   .   .   . |
         +-------------------+
    
    0 讨论(0)
提交回复
热议问题