Reputation: 57
I want to loop through multiple variables (ie multiple haystacks) using a list of needles.
Data:
PICK1 | PICK2 | PICK3 | PICK4 |
---|---|---|---|
Grape | Raspberry | Clementime | Strawberry |
Strawberry | Lemon | Blueberry | Apple |
Cantelope | Mango | Grape | Pear |
Apple | Orange | Kiwi | Raspberry |
Manual code that works
Compute citrus=0
if char.index(PICK1,"orange")>0 citrus=1.
if char.index(PICK2,"orange")>0 citrus=1.
if char.index(PICK3,"orange")>0 citrus=1.
if char.index(PICK4,"orange")>0 citrus=1.
if char.index(PICK1,"lemon")>0 citrus=1.
if char.index(PICK2,"lemon")>0 citrus=1.
if char.index(PICK3,"lemon")>0 citrus=1.
if char.index(PICK4,"lemon")>0 citrus=1.
if char.index(PICK4,"clementine")>0 citrus=1.
if char.index(PICK4,"clementine")>0 citrus=1.
if char.index(PICK4,"clementine")>0 citrus=1.
if char.index(PICK4,"clementine")>0 citrus=1.
Desired Outcome: log 1 if the values are found within the variables
Citrus |
---|
1 |
1 |
0 |
1 |
Attempted code (not working)
do repeat L = [orange, lemon, clementine]
/PICK = PICK1 to PICK7000.
compute L = if char.index(PICK,L)>0 citrus=1.
end repeat.
I originally put the char.index to search for multiple values with a similar basename. For example, searching "berry" would desire to find "strawberry", "blueberry", etc. Is there a way to incorporate that into the COMPUTE
function?
NUMERIC berry (f1.0).
DO REPEAT PICK = PICK1 to PICK7000.
COMPUTE berry=any(PICK, char.index(PICK, "berry").
END REPEAT.
EXECUTE.
Upvotes: 2
Views: 124
Reputation: 3166
The do repeat
structure operates with arrays which must be of equal lengths. On top of that, you do not need square brackets, and strings are referenced between quotations signs. Also, not sure if the compute
really works like that, mixed with and if
transformation.
You want to parse a list of variables, check for 3 strings, and do a transformation if condition is met:
NUMERIC citrus (f1.0).
COMPUTE citrus=0.
DO REPEAT PICK = PICK1 to PICK7000.
IF any(PICK, "orange", "lemon", "clementine") citrus=1.
END REPEAT.
EXECUTE.
or, a little more synthetic:
NUMERIC citrus (f1.0).
DO REPEAT PICK = PICK1 to PICK7000.
COMPUTE citrus=any(PICK, "orange", "lemon", "clementine").
END REPEAT.
EXECUTE.
or, if you want to also look at any "berries":
NUMERIC citrus (f1.0).
NUMERIC berries (f1.0).
DO REPEAT PICK = PICK1 to PICK7000.
COMPUTE citrus=any(PICK, "orange", "lemon", "clementine").
COMPUTE berries = CHAR.INDEX(PICK, "berry")>0.
END REPEAT.
EXECUTE.
Upvotes: 2