SPSS Tutorials

BASICS REGRESSION T-TEST CHI-SQUARE TEST ANOVA

Select Variables by Variable Labels

Question

"I'd like to calculate the mean over all variables that have the "How would " in their variable labels. What's a good way to do so?

The reason is that I have data in which some variables are ratings for different quality aspects. The variable labels for all of them contain the string "How would ". None of the other variables in my data have a variable label containing this string. How can I compute the mean over all ratings and none of the other variables? Can I also label the new variable automatically?"

Solution

*Find the variables the target pattern in their labels and print them for inspection.

begin program.
targetPattern = 'How would ' #Specify target pattern.
import spss
varList = [spss.GetVariableName(v) for v in range(spss.GetVariableCount()) if targetPattern in spss.GetVariableLabel(v)]
print varList
end program.

*If the selection of variables is correct, compute their mean as a new variable.

begin program.
new_variable = 'mean_rating' #Specify a name for the new variable.
spss.Submit('''
compute %s=mean(%s).
variable label %s 'Mean over (%s).'.
exe.'''
%(new_variable,','.join(varList),new_variable,' '.join(varList)))
end program.

Description

Previous tutorial: Strip Prefix from Variable Labels

Next tutorial: Prefix Many Value Labels

Let me know what you think!

*Required field. Your comment will show up after approval from a moderator.