问题
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