2

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

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

我看了一下DO REPEATand LOOPwithVECTOR命令,但我似乎并不完全理解它们是如何工作的。我无法将在线阅读的其他示例中的解决方案转移到我的问题中。我会对只循环一组变量并执行任务的解决方案感到满意,然后我会为我的其他 13 组变量适当地调整语法。希望你能帮助我。

4

2 回答 2

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.
于 2016-05-26T11:29:01.823 回答
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.
于 2016-05-27T14:24:21.583 回答