joshuaf59
joshuaf59

Reputation: 65

Recoding a variable based on a list or set of values?

Is there syntax in SPSS that looks in a list or set of values? I have been unable to find a syntax that will use a list/set as reference.

One use example is recode;

DATASET ACTIVATE DataSet1.
STRING V2 (A8).
RECODE V1 ('a' = 'group1') ('b' = 'group1') ('c' = 'group1') INTO V2.
EXECUTE.

Instead of typing each value like above, I would to use an function like the SQL IN, if it exists.

Logic:

if V1 IN (a,b,c,e...) then V = "group1"...

Thank you!

Upvotes: 4

Views: 1028

Answers (1)

eli-k
eli-k

Reputation: 11350

Here are some possibilities and examples to get you started:

Your recode command could be more compact, like this:

recode V1 ('a' 'b' 'c'='group1') ('d' 'e' 'f'='group2') INTO V2.

The any function gives you a logical value. For example:

if any(V1,'a', 'b', 'c') [do something]. /* can also use DO IF.

or

compute group1=any(V1,'a', 'b', 'c').

If you want to search for strings within values, you can use char.index this way (in this example the search string 'abc' is split into one character strings, so V1 is tested for containing each of 'a', 'b' and 'c' separately):

if char.index(V1,'abc',1)>0 V2='group1'.

for more complex options you can loop over values with loop or do repeat. For example, this loop will give V2 the value of 'grp1' for every value of V1 that contains 'a', 'b' or 'c', 'grp2' if V1 contains 'd', 'e' or 'f':

do repeat MyStr='a' 'b' 'c' 'd' 'e' 'f'/grp='grp1' 'grp1' 'grp1' 'grp2' 'grp2' 'grp2'.
   if char.index(V1,Mystr)>0 v2=grp.
end repeat.

Upvotes: 4

Related Questions