Search code examples
spss

Filter the first n cases in SPSS based on condition


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!


Solution

  • 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.