Filter the first n cases in SPSS based on condition

Viewed 38

I have a database in SPSS structured like the following table:

ID Gender Age Var1 Var...
1 0 7 3 ...
2 1 8 4 ...
3 1 9 5 ...
4 1 9 2 ...

I want to select only the first n (e.g.: 150) cases, where Gender = 1 and Age = 9, so in the table above the 3. and 4. case. How can I do it? Thanks!

2 Answers
compute filter_ = $sysmis.
compute counter_ = 0.

if $casenum=1 and (Gender = 1 and Age = 9) counter_ =1 .
do if $casenum <> 1.
    if ~(Gender = 1 and Age = 9) counter_ = lag(counter).
    if (Gender = 1 and Age = 9) counter_ = lag(counter) +1.
end if.
compute filter_ =  (Gender = 1 and Age = 9 and counter<= 150).
execute.

I am not sure if this is the most efficient way, but it gets the job done. We use the counter_ variable to assign an order number for each record which satisfies the condition ("counting" records with meet the criteria, from the top of the file downwards). Then create a filter of the first 150 such records.

The below will select the first 150 cases where gender=1 AND age=9 (assuming 150 cases meet that criteria).

N 150.
SELECT IF (Gender=1 AND Age=9).
EXE .

Flipping the order of N and SELECT IF () would yield the same result. You can read more about N in the IBM documentation

Related