Pull data from SPSS dataset, process in R and push results back as a Pivot Table
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 | * 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. |
26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 | 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 |
46 | END PROGRAM.
|
Related pages
...
Navigate from here