3

I have two sets of 8 variables each. I want to multiply the first(second, third etc.) element of each list and sum up the products. So far my attempt is this:

DO REPEAT
  set1 = var1 to var8.
  set2 = varA to VarH.
  compute sum_of_products = SUM(set1 * set2).
END REPEAT.
EXECUTE.

The Error I get is (roughly translated from german):

Error code 4285 in row 38. String: set2

Wrong variable name: either name is longer than 64 chars or he is not defined by a previous command.

Execution of this command has been stopped.

I assume the problem is, that my DO REPEAT does not properly wrap around the commands, but I was not able to manage the right solution with the documentary, as well as with google search. These DO REPEATS and LOOPS really give me a headache.

eli-k
  • 10,898
  • 11
  • 40
  • 44
Dekay
  • 147
  • 1
  • 9

2 Answers2

2

See correct syntax for the DO REPEAT command:

compute sum_of_products=0.
DO REPEAT set1 = var1 to var8 /set2 = varA to VarH.
  compute sum_of_products = sum(sum_of_products , (set1 * set2)).
END REPEAT.
EXECUTE.
eli-k
  • 10,898
  • 11
  • 40
  • 44
  • Note, using the addition (`+`) operator over the `SUM` function will result in the derived variable being assigned missing for any case with missing data in any of the variables being used in the computation. If wanting to derive the product sum score despite missings then simply using the `SUM` function would alleviate this. – Jignesh Sutar Jun 16 '16 at 11:30
  • @Jignesh Sutar you are right, better idea to use `sum` here. Edited my answer accordingly. – eli-k Jun 16 '16 at 12:25
  • Thanks a lot for the answer! What if I don't want to compute the sum of the products, but add up all the values of set1 if set2 meets a certain condition (e.g. add value of set1 only when set2 > 1?). – Dekay Jun 19 '16 at 14:36
  • `compute NewVar=0.` and then inside the DO REPEAT add `if set2>1 NewVar=sum(NewVar, set1).` – eli-k Jun 20 '16 at 04:13
2

You are very close. Below is mock example dataset with solution:

* Generate mock data*.
INPUT PROGRAM.
NUMERIC ID S1_1 TO S1_8 S2_1 TO S2_8 (F3.1). 
LOOP ID=1 TO 10.
  DO REPEAT S1=S1_1 TO S1_8 /S2=S2_1 TO S2_8.
    COMPUTE S1=RND(RV.F(3,10)).
    COMPUTE S2=RND(RV.F(3,10)).
  END REPEAT.
END CASE.
END LOOP.
END FILE.
END INPUT PROGRAM.


DO REPEAT S1=S1_1 TO S1_8 /S2=S2_1 TO S2_8 /S=#S_1 TO #S_8.
    COMPUTE S=(S1*S2).
END REPEAT.
COMPUTE PS=SUM(#S_1 TO #S_8).
Jignesh Sutar
  • 2,909
  • 10
  • 13