Search code examples
spss

Copy variable between SPSS Datasets using Syntax


EDITED based on feedback...

Is there a way to copy a variable form one open dataset to another in SPSS? What I have tried is to create a scratch variable that captures the value of the variable, and use that scratch variable in a Compute command into the next dataset:

DATASET ACTIVATE DataSet1.
COMPUTE #IDSratch = ID.
Dataset Activate DataSet2.
Compute ID = #IDScratch.

This fails because activating Dataset2 causes the scratch variable to be dropped from memory.

Match Files and/or STAR JOIN syntax will work for most scenarios but in my case because Dataset1 has many more records than Dataset2 AND there are no matching keys in both datasets, this yields extra records.

My original question was "Is there a simple, direct way of copying a variable between datasets?" and the answer still appears to be that merging the files via syntax is the best/only method if using syntax.


Solution

  • Since SPSS version 21.0, the STAR JOIN command (see documentation here) allows you to use SQL syntax to join datasets. So basically, you could get only the variables you want from each dataset.

    Assume your first dataset is called data_1 and has id and var_1a. Your second data is called data_2, has the same id and var_2a; and you just want to pull var_2a to the first dataset. If both datasets are open, you can run:

    dataset activate data_1.
    STAR JOIN
      /SELECT t0.var_1a, t1.var_2a
      /FROM * AS t0
      /JOIN 'data_2' AS t1
        ON t0.id=t1.id
      /OUTFILE FILE=*.
    

    The link I provided above has plenty of examples on how to join variables of files that are saved in your computer.