Author: Steve Sizmur

* Sent by Steve Sizmur PhD, Chief Statistician at Picker Institute Europe.
* February 12, 2015.

***--Comments below by A.B.
* The R code within BEGIN PROGRAM R - END PROGRAM block illustrates how to read data 
* for a set of variables (var1 to var4) from SPSS dataset, get the variable information 
* (in particular, measurement level) from SPSS and then process them - in this case 
* to create a correlation matrix. The matrix then send back to SPSS to be displayed as Pivot Table.

* Reading measurement is needed here to define the right type of correlation to compute in hetcor function of R.
* Subject matter: hetcor function from 'polycor' package returns different type of correlation (Pearson, polyserial, polychoric) 
* depending if  variables are continuous, or nominal or ordinal. 

* NB! If you'd like to reproduce subject matter part of code to compute correlations,
* note, that 'psych' and 'polycor' packages are employed here.
* You may need to install packages before the first run. One option is:
*BEGIN PROGRAM R.
*install.packages("psych")
*install.packages("polycor")
*END PROGRAM.
* If you chose to install packages in this way (from within SPSS syntax calling R), check for the dialog boxes
* that might be opened after the code run, waiting for your input.
***--End of A.B. comments.

BEGIN PROGRAM R.
library(psych) # not essential but useful for the headTail command
library(polycor)
tempdata <-spssdata.GetDataFromSPSS(variables="var1 var2 var3 var4") # creates an R data frame
vardict<-spssdictionary.GetDictionaryFromSPSS(variables="var1 var2 var3 var4") # gets variable definitions
headTail(tempdata,hlength=4,tlength=4,digits=2) # gives printout to ensure all looks correct

# Make sure correct variable level is registered
for (i in 1:length(tempdata)) {
   if (vardict["varMeasurementLevel",i]=="scale") tempdata[,i]<-tempdata[,i]
   else
   if (vardict["varMeasurementLevel",i]=="nominal") tempdata[,i]<-factor(tempdata[,i])
   else
   if (vardict["varMeasurementLevel",i]=="ordinal") tempdata[,i]<-ordered(tempdata[,i])
}
tempdata.cor <- hetcor(tempdata, ML = FALSE, std.err = FALSE, use = c("complete.obs"), bins=4, pd=TRUE) # compute correlations
spsspivottable.Display(tempdata.cor$type, title="Correlation type") # output the matrix in SPSS output window
poly.cor <- as.matrix(tempdata.cor) # put correlations into a matrix for other operationa
sm.cor <- cor.smooth(poly.cor) # smooth the matrix - may be needed for factor analysis
spsspivottable.Display(sm.cor) # output the smoothed matrix
END PROGRAM.

Published: Jan. 12, 2015. Updated: June 11, 2015.