Using a variable in a conditional sentence

2019-07-14 15:26发布

问题:

I want to save a value in a variable and then use it in a conditional sentence. To clarify this I'll give you a simpler example: Imagine that I have a database with the kind of animal(dogs and cats),their age(1 or 2) and their weight. I want to do the following conditional:

IF( animal=dog & age=1 & weight>= percentile75 ) Wdogs=1.
EXECUTE.
IF( animal=dog & age=1 & weight<percentile75) Wdogs=0.
EXECUTE

I want to calculate percentile75 automatically and save in a variable so I can use the code in any database I have. Also I want to rewrite the variables if I change the database and execute the code. Is there a way to do this?

Thanks a lot

回答1:

You can use RANK in order to divide the weights into n groups. The command creates a new rank variable which you can then use in your conditionals. For the ranking to be done separately in each relevant sub-group, use the BY sub-command. In your example, each animal/weight subgroup will be ranked separately into weight quartiles, and the subsequent command will use the new variable:

RANK VARIABLES=weight (A) BY animal weight/NTILES(4).
IF(animal=dog & age=1 & Nweight=4) Wdogs=1.
IF(animal=dog & age=1 & Nweight<=3) Wdogs=0.
EXECUTE.

You can save a line of syntax by using (instead of the two if commands):

IF(animal=dog & age=1) Wdogs=(Nweight=4).


回答2:

First thing mate is lose those EXECUTE commands (They are unnecessary and betray you as a noob point and clicker with default options). From other posts I discern you need to do that with multiple variables. Simplify your life by boning up on VARSTOCASES, maintain the current RANK with BY and put a f'ing Shrimp (or a PRAWN) on the Barbie Queue.



标签: spss