SPSS:根据分数总结多个变量分数

时间:2016-05-26 08:59:25

标签: loops spss recode

tl; dr:我需要先将一组变量二分为0/1,然后总结这些值。我需要为14x8变量执行此操作,因此我正在寻找一种循环方式。

大家好,

我有一个非常具体的问题,我需要你的帮助:

问题描述: 在我的数据集中,我有14组,每组8个变量(例如a1到a8,b1到b8,c1到c8等),分数范围从1到6.注意,变量是非连续的,其间有字符串变量他们(我需要用于不同的目的)。

我知道想要计算每组这些变量的分数(例如scoreA,scoreB,scoreC)。分数应根据以下规则计算:

scoreA = 0.
If a1 > 1 then increment scoreA by 1.
If a2 > 1 then increment scoreA by 1.
... etc.

实施例: 数据集:

1 5 6 3 2 1 1 5

1 1 1 3 4 6 2 3

分数:

5

5

我以前的尝试: 我知道我可以通过首先重新编码变量来对它们进行二分,然后总结这些值来完成这项任务。这对我来说有两大缺点:首先它创造了许多我不需要的新变量。其次,这是一个非常繁琐和重复的任务,因为我有多组变量(具有不同的变量名称),我需要用它来执行相同的任务。

我用VECTOR命令查看了DO REPEAT和LOOP,但我似乎并不完全了解它们是如何工作的。我无法将我在线阅读的其他示例中的解决方案转移到我的问题中。 我很满意只有一组变量循环并完成任务的解决方案,然后我会适当调整其他13组变量的语法。希望你能帮助我。

亲切的问候, 大卫

2 个答案:

答案 0 :(得分:1)

参见两个解决方案:一个循环遍历每个集合,第二个是循环遍历集合列的宏:

* creating some sample data.
DATA LIST list/a1 to a8 b1 to b8 c1 to c8 hello1 to hello8.
BEGIN DATA
1 1 1 1 1 1 1 2 1 1 1 1 1 1 2 2 1 1 1 1 1 3 3 3 1 1 1 1 4 4 4 4 
1 1 1 1 2 3 4 5 1 1 1 2 3 4 1 0 0 0 0 0 1 2 1 2 3 2 1 2 3 2 1 6
END DATA.

* solution 1: a loop for each set (example for sets a, b and c).
compute scoreA=0.
compute scoreB=0.
compute scoreC=0.
do repeat 
   a=a1 a2 a3 a4 a5 a6 a7 a8
   /b=b1 b2 b3 b4 b5 b6 b7 b8
   /c=c1 c2 c3 c4 c5 c6 c7 c8./* if variable names are consecutive replace with "a1 to a8" etc'.
 compute scoreA=scoreA+(a>1).
 compute scoreB=scoreB+(b>1).
 compute scoreC=scoreC+(c>1).
end repeat.
execute.

为14个不同的集合执行此操作并不好玩,因此假设您的集合始终命名为$ 1到$ 8,您可以使用以下宏:

define DoSets (SetList=!cmdend)
 !do !set !in (!SetList)
   compute !concat("Score_",!set)=0.
   do repeat !set=!concat(!set,"1") !concat(!set,"2") !concat(!set,"3")      !concat(!set,"4") !concat(!set,"5") !concat(!set,"6") !concat(!set,"7")           !concat(!set,"8").
     compute !concat("Score_",!set)=!concat("Score_",!set)+(!set>1).
   end repeat.
 !doend
 execute.
!enddefine.

* now call the macro and list all set names.
DoSets  SetList= a b c hello.

答案 1 :(得分:1)

上面的do repeat循环工作得很好,但是有很多变量集,创建起来会很繁琐。使用Python可编程性,可以​​自动生成,而无需考虑变量顺序。下面的代码假设无限数量的变量,其名称形式为小写字母数字,以8个为一组出现,并生成并运行do repeat。为简单起见,它为每个输出变量生成一个循环,但这些循环都将在单个数据传递上执行。如果名称模式不同,则可以调整此代码,如果您说出它是什么。

begin program.
import spss, spssaux
vars = sorted(spssaux.VariableDict(pattern="[a-z]\d").variables)

cmd = """compute %(score)s = 0.
do repeat index = %(vlist)s.
compute %(score)s = %(score)s + (index > 1).
end repeat."""

if len(vars) % 8 != 0:
   raise ValueError("Number of input variables not a multiple of 8")

for v in range(0, len(vars),8):
  score =  "score" + vars[v][0]
  vlist = " ".join(vars[v:v+8])
  spss.Submit(cmd % locals())
end program.
execute.