SPSS syntax is a must!

Are you aware of the book SPSS Programming and Data Management?

Don't satisfy yourself with the Graphic User Interface (GUI)!

The GUI is fine (I use it every day); however, using syntax in addition of the GUI can easily increase productivity by a factor of 5 to 10 times for simple jobs. The increase can easily be 50 times or more for larger, complex jobs. Furthermore some of SPSS's features are only available through syntax. As a "bonus", syntax files work on all versions of SPSS, not just on Windows.

There is something for everybody in the sample syntax's included here:

Suggestions and code contributions are welcomed. Share what you know! Learn what you don't!

The syntax files are broadly classified by purposes as follows:

  1. Area Under the Curve (AUC)
  2. Batch files
  3. Block Designs
  4. Bootstrap and random numbers
  5. Charts and Tables
  6. Cluster Analysis
  7. Combinations, permutations, interactions
  8. Compute
  9. Concatenate/modify string variables (see also Parse or flag data)
  10. Data Editor
  11. Data validation
  12. Dates and time (see also the Dates, Time and Age Tutorial)
  13. Distributions, Confidence Interval
  14. Export import (see also the FAQ)
  15. Factor analysis
  16. Flag or select Cases
  17. IGRAPH (see also the corresponding script section)
  18. Item Analysis
  19. Labels, variable names and format
  20. Matching data files
  21. Matrix
  22. Meta Analysis
  23. Multiple responses
  24. OMS
  25. Outliers
  26. Parse or flag data (see also String Manipulation Tutorial)
  27. Random sampling
  28. Ranking, largest values, sorting, grouping
  29. Read write or create data
  30. Regression, repeated measures
  31. Remove characters, duplicates or variables
  32. Restructure file
  33. ROC curves
  34. Sample Size, Power
  35. Self adjusting syntax
  36. Strings
  37. Survival Analysis
  38. Tests of inequality
  39. Test if file or variable exists
  40. Time Series
  41. Transform variable
  42. T-Test or Means or ANOVA
  43. Unclassified
  44. Working with many files (see also the corresponding script section)
  45. Working with missing values

 

I have not necessarily checked each and every file found here. I have grabbed some files which looked interesting but I might not have had the time to review them up to now. So much code...so little time...

When the information is readily available, I show the name of the authors of syntax I did not write. Usually , I do not show email addresses in order to reduce the number of emails to authors.  If somebody objects to having his / her code or name listed, please send me an email and I will quickly remove the reference. If, on the other hand, you send me code which would be useful to other visitors, I will gladly include it here with due credit. Such code should contain dummy data (ideally using DATA LIST or INPUT PROGRAM) and a description of its purpose.

 


 

** Important Download Instructions **

 

Note: At the suggestion of a visitor, I have changed the extension of the *.sps files to *.txt, this makes it easier to look at the files online. When you click on an *.sps file below, it opens up in your browser as a text file. If you like what you see, go back to the prior page, (do not close the syntax window) right click on the file name and select "Save target as").

Simply selecting and copying the syntax and subsequently pasting it into an SPSS syntax window often results in the loss of line breaks; all command lines are saved consecutively in the same line, this is not very useful   :-(

 


If you don't measure it...you can't improve it!


Note: Files with a at the end were added or modified less than 30 days ago.

 

  1. Area under the curve using Trapezoidal Integration.SPS
  2. Incremental Area under the curve.SPS

Top

  1. Example of bat file running an sps file
  2. Run syntax from batch file or command line.SPS

Top

  1. Completely Randomized Designs.SPS (equal or unequal n per treatment)
  2. Random assignment of units to experimental treatments.SPS This is for Randomized Block Designs (Simple & Generalized) and Completely Randomized Designs (equal n per treatment)

Tip: any time you use random numbers and need to be able to reproduce your results, use "SET SEED=number." at the beginning of your syntax where 'number' is any 'random number' you come up with. One option is to use the current date & time (e.g. "SET SEED=1120722." if it is 7h22 on Nov 20th)

  1. Bootstrap confidence interval for the variance of a variable.sps
  2. Bootstrap confidence interval for Cronbach alpha.SPS
  3. Bootstrap crosstab.SPS
  4. Bootstrap ordinary least square (OSL) estimators.SPS
  5. Bootstrap the mean and median.SPS
  6. Generating multinominal random variables.SPS(AnswerNet)
  7. Generating multivariate hypergeometric random variables.SPS (AnswerNet)
  8. Generating multivariate normal variables with a specific covariance matrix (AnswerNet)
  9. Generate random triad numbers.SPS
  10. Get random sample of various size then calculate statistics.SPS (Compare means of n samples of size s1 s2 ... sn ...)
  11. Get various random samples of same size calculate statistics.SPS (Compare means of n1 n2 ... nn samples of size s)
  12. Sampling distribution of the correlation between 2 variables.SPS  

    Bootstrapping using OMS (this requires v12)
  13. oms_bootstrapping.sps

Top

  1. Bar charts for school types by sex where percentages of each sex add up to 100 percent.SPS
  2. Blank bar for unselected category.SPS (from AnswerNet) 
  3. Blank bar for unselected category (generalized).SPS (note however that to show empty categories in CTABLES is trivial. All that is required is to specify EMPTY=INCLUDE in the /Categories subcommand) 
  4. Compare (superimpose) two histograms.SPS could also use a population pyramid (see IGRAPH section below for an example)
  5. Count outliers.SPS (show number of outliers in a boxplot)
  6. Do bar charts excluding categories with small number of cases.SPS
    This macro is fully commented here.
    Newbie's who do not know how to use a macro should read this explanation.
  7. Do many histograms with the same axis boundaries.SPS (this demonstrates how the use of the macro Dograph.sps and template Dograph.sct to produce many graphs with the same x and y scale.
  8. Graph cumulative percentage retired at attained age by categorical variable.SPS
  9. Graph cumulative percent on X axix.SPS
  10. Graph survey question.SPS
  11. Histogram with percent on y axis instead of numbers.SPS
  12. Identify your own data in the chart.SPS
  13. Identify your own data in the chart version2.SPS This is a generalization of the above syntax. It uses the following chart template Identify Your Own Data.sct (right-click on this template and select save target)
  14. Print current date in chart title.SPS
  15. Print current date and time in chart title.SPS (Same technique can be used with Tables)
  16. Print histogram or bar chart depending on data.SPS(A good macro example)
  17. Print school names as part of graph titles.SPS
  18. Show mean values in line graph.SPS
  19. Show 2 categories on same histogram.SPS
  20. ZIPF law and graph.SPS

    Tables
  21. Construct a table "manually" in the data editor.SPS(A good example of data restructuration)
  22. Construct a table "manually" example no 2.SPS
    (non trivial code...)
  23. Find population frequency when multiple response with long strings.SPS
  24. List variables in frequency table by order of medians.SPS
  25. Print actual name group and id in heading of each listing.SPS
  26. Print mean plus minus standard deviation in Table.sps
  27. Put 4 variables in the same frequency table.SPS
  28. Show empty category in tables.SPS (from AnswerNet) Note: This is trivial with CTABLE)
  29. Show empty categories in tables (second method).SPS
  30. Show mean values.SPS
  31. Show number of valid cases in table footnote.SPS
  32. Table where list of variables is generated by macro.SPS (Illustrates the !IF ...!ELSE ... !IFEND macro command)

  33. CTABLES
  34. Get statistics for grouping of variables.SPS
  35. Sort categories by decreasing count but with Others as last one.SPS
  36. Using Macros and CTABLE.SPS

Top

  1. Cluster analysis using similarity proximity (count) data as input.SPS
  2. Save centers of Hierarchical cluster analysis as initial value of K-means.SPS

Top

  1. All combinations of 3 numbers out of n.SPS (see "Find all Combinations .." below for a generalization)
  2. All combinations of 3 letters out of n.SPS (with replacement)
  3. Calculate interaction terms between 2 categorical variables.SPS (within a regression context)
  4. Create a new variable for each combination of 2 variables.SPS
  5. Find all combinations of 1 up to n items out of m items.SPS (high power stuff!)
  6. Find all combinations of n items out of m items.SPS (high power stuff!)
  7. Find all permutations of integers 1 to n.SPS Maximum value of n is 7. Combined with recode, this can find permutations of any strings or numbers.
  8. Generate orders for block of trials.SPS
  9. Get all possible crossproducts of pairs of variables.SPS (contains a fair amount of comments)

Top

  1. Automatically compute sample weights to approximate population.SPS
  2. Box-CoxTransformation.SPS To transform var1 using each of the 31 values of lambda that are between -2 and 1 (increments of 0.1).
  3. Count number of distinct values across 400 variables.SPS
  4. Compute percentage of patients having each fracture category.SPS 
  5. Compute z = x / max( y) where max( y) is over all cases.SPS (it is sometimes preferable to use this macro technique)
  6. Compute distances between 2 points on earth.SPS (with thanks to Simon Freidin)
  7. Compute average of m variables where m is a variable in the data file.SPS
  8. Create a new variable equal to mean of an other variable.SPS
  9. Find the cubic root.SPS  
  10. Reverse the digits on an integer.SPS
  11. Weight data based on 2 or more vars.SPS With thanks to Jo„o Duarte!

Top

  1. Apparent problem with concat.SPS Newbies should take a look at this example.
  2. Combine a string variable and a numeric variable.SPS
  3. Concatenate.SPS (new string equals concatenation of values in second variable)
  4. Concatenate content of cases with same id.SPS  
  5. Concatenate numbers.SPS
  6. Concatenate 22 variables.SPS
  7. Convert first letter of each word to upper case.SPS (Thanks to A. Paul Beaulne for sending me this code)
  8. Create an id using name and dob.SPS
  9. Normalise alpha.sps (Capitalise the first letter of each word, use lower case for the other letters)
  10. Normalize string.SPS (delete spaces at beginning, remove period at end, capitalize all letters)
  11. Remove initial from name.SPS
  12. Remove period from string.SPS(can be modified to remove any other characters)
  13. Reorganize names.SPS (place family name at the beginning of the sting)
  14. Transform ascii codes into characters.SPS

Top

  1. Reduce size of columns in data editor.SPS  
  2. Right align strings in data editor.SPS

Top

  1. Perform tests on ssn.SPS
  2. Validate likert and continuous values.SPS
  1. Add 60 days to a date then find end of that month.SPS 
  2. Add leading zeros to a string date.SPS
  3. Ages are in nnH nnD nnM and nnA.SPS 
  4. Break down number of days in hospital by calendar month.SPS
  5. Calculate age.SPS
  6. Calculate time differences to milliseconds.SPS 
  7. Calculate mean date and standard deviation in days.SPS
  8. Calculate nb of days within the eligibility period.SPS
  9. Caculate number of minutes between 2 timestamps (crossover midnight).SPS  
  10. Calculate number of months between 2 dates.SPS
  11. Calculate waiting time when time is coded in hh min.SPS
  12. Compute number of weekdays between 2 dates.SPS
  13. Compute number of weekdays excluding public holidays.SPS
  14. Compute sleep time.SPS
  15. Convert basis.SPS
  16. Convert strings into numbers.SPS (variable contains age in either of the following format "7 Y" for 7 years, "3m" for 3 months, "28D" for 28 days. Need to convert these to years.)
  17. Convert string formated as hhmmss into numeric time variable.SPS (thanks to Jim Marks)
  18. Convert string 01jan1992 to a date variable.SPS
  19. Convert string 1997-08-22 into a date variable.SPS
  20. Convert string into date and time variables.SPS  
  21. Convert string "2006-04-28 18:20:01" to datetime format.sps
  22. Convert string to date and select cases which fall during the weekend.SPS
  23. Convert string "04Apri03" to a date variable.SPS
  24. Date plus 3 months.SPS
  25. Dates appear as asterix on chart.SPS (solution)
  26. Extract time portion from string variable containing date and time.SPS
  27. From AM PM to military time.SPS
  28. Importing from excel (convert days into dates).SPS
  29. Keep time portion of date when creating Tab delimited file.SPS
  30. Make variable equal to current date.SPS
  31. Number of consecutive 30 minutes of hypoxia.SPS
  32. Print current date as part of graph title.SPS
  33. Print date and time before a procedure.SPS
  34. Print day name along with date.SPS
  35. Read time stamp.SPS
  36. Save data file with current date as part of name.SPS
  37. Select a range of dates.SPS
  38. Time an SPSS procedure.SPS

Top

  1. Add variables containing lower and upper CI for mean.SPS 
  2. Bayes estimates for proportions and their CI.SPS with thanks to Evgeny Ivashkevich (this also calculates Confidence Intervals for a category not present in the sample)
  3. Calculate Chi-square significance given q and df.SPS 
  4. Calculate 95 percent confidence interval for the median.SPS (thanks to Marta Garcia-Granero)
  5. Calculate McNemar Chi-Square test.SPS(thanks to Marta)
  6. Hodges Lehmann Confidence Interval for Median difference.SPS (thanks to Marta Garcia-Granero)
  7. Exact confidence limits for a binomial parameter.sps 
  8. Goodness of fit test for Poisson Distribution.SPS (thanks to Marta Garcia-Granero)
  9. Normalization of raw scores (with thanks to Valentim R. Alferes)
  10. Proportion tests and confidence intervals.SPS (thanks to Gwilym Pryce) This includes large-sample
    - significance test for a single population proportion
    - confidence interval for a single population proportion
    - significance test for two population proportions
    - confidence intervals for comparing two population proportions
  11. Testing linear constraints in MR.SPS with thanks to Johannes Naumann. This macro tests General Linear hypothesis of the type cb=d, where b is a vector of regression coefficients and c is a matrix of linear constraints.
  12. Univariate and multivariate tests of skew and kurtosis (a link to Lawrence T. Decarlo's SPSS macro). The same site also contains
    - SPSS macro for Mardia's multivariate skew
    - SPSS programs for signal detection models expressed as generalized linear models 

    Fitting distributions
  13. Fitting models with overdispersion or 'extra-Poisson' variation.SPS

Top

  1. Export all tables in word.SPS (see Sample Scripts for an automated solution)
  2. Export data and value labels to excel.SPS 
  3. Export content of data editor to a specified sheet of an existing Excel workbook.SPS
  4. Export from SPSS to ACCESS.SPS
  5. Export from SPSS to ACCESS (method2).SPS
  6. Export more than 256 vars to Excel.SPS
  7. Export some SPSS vars to many sheets of Excel workbook.SPS
  8. Import from ACCESS or LotusNotes.SPS (no DSN needed: this is very handy. Thanks to Tom Dierickx)
  9. Writing back an SPSS 10 file to an ODBC database.SPS (from AnswerNet)

Top

  1. Determining the number of components using parallel analysis and Velicer's MAP test (a link to Brian P. O'Connor's site)
  2. Factor analysis with Spearman correlation through a matrix.SPS

Top

  1. Exclude "outliers" from analysis.SPS (where outliers are defined as cases outside Mean +/- 2 SD)
  2. Flag cases where a given string variable contains a given word.SPS  
  3. Flag cases where any of a list of variables have same value.SPS
  4. Flag cases where salary is in top 95 percentile.SPS  
  5. Flag cases meeting a certain condition as well as preceding and following case for the same person.SPS
  6. Flag first and last dates (within each ID).SPS
  7. Keep only duplicate cases.SPS
  8. Print frequency table of the n most (less) frequent items.SPS
  9. Select patients where drug1 was given before drug2.SPS
  10. Select cases where same letter appears twice in string.SPS
  11. Sophisticated search in string variable.SPS (data were scanned, portion of strings include letters (eg B) instead of numbers (eg 8); this syntax flags the errors)

Top

  1. Clustered bars with percent based on total in cluster.SPS
  2. Example of surface plot.SPS
  3. Graphing an arbitrary function.SPS
  4. Graph showing interaction in multiple regression.SPS
  5. How to speed up IGRAPH.SPS (A similar approach could be used for other type of graphs)
  6. Population pyramids.SPS
  7. Produce long IGRAPHs.SPS
  8. Separate box plot graph for each category value.SPS (syntax can be adapted to any other type of graph)

Top

  1. Syntax for item analysis.SPS This is based on SPSS's White Paper on Item Analysis and on this Exercise data file.
  2. Syntax For Item Analysis V6.sps This is a much improved version of the above. It is fully automated and has been developed and tested using SPSS 15. 
  1. Add (or replace) a character at the beginning of each var names.SPS
  2. Add '_99' at the end of every variable names.SPS
  3. Apply lab1 as value label to var1 by syntax.sps
  4. Assign same label to many variables.SPS
  5. Assign value labels to a vector.SPS
  6. Assign variable and value labels of a given variable to other variables.SPS
  7. Automatically rename variables.SPS
  8. Auto variable renaming or copying.SPS  
  9. Change case of Var Labels and/or Value Labels.SPS with thanks to Simon Freidin
  10. Change format of 600 variables.SPS
  11. Convert variable format.SPS (see also the following tutorial. If you are not familiar with macros, see this macro tutorial for newbies).
  12. Create dummy variables.SPS (also called indicator or binary variables)
  13. Create dummy variables (AnswerNet).SPS
  14. Create new variable equal to number of occurrences of var1.SPS
  15. Define a global variable.SPS (this is a useful programming technique)
  16. Define variable label by Macro.SPS
  17. Delete all variable labels of a given sav file.SPS
  18. DeleteListOfVariableNames But Some May Not Exist.SPS
  19. Delete variables with all values equal to zero.SPS
  20. Delete or reorder variable names (data fields).SPS
  21. Delete many variable labels.SPS
  22. Group data and define corresponding value labels.sps
  23. Define list of variables between two variables.SPS (a macro Gem)
  24. Match label file with data file.SPS
  25. Print variable labels and value labels in FREQ Tables.SPS
  26. Read ASCII data variable name, value and value labels.SPS
  27. Recode variables var1 becomes varx etc.SPS
  28. Remove underscores from all variable names.SPS (can be adapted to remove any other character)
  29. Rename variables.SPS
  30. Rename all variables t2abc becomes t1abc etc.SPS
  31. Rename var in file1 to names in file2.SPS
  32. Reverse scale and value labels.SPS
  33. Round and change format of all numeric variables.SPS
  34. Show 0.45 instead of .45.SPS
  35. Sort variable names by alphabetical order (AnswerNet).SPS
  36. Sort variables by name in data file.sps (sent by A. Paul Beaulne)
  37. SortVariablesByAlphabeticalOrder.sps
  38. Write value labels to ASCII file (AnswerNet).SPS
  39. Xpand vector names.SPS

Top

  1. Compare 2 data files.SPS with thanks to Simon Freidin
  2. Create data file if double entries are equals.SPS (where entries done by 2 different persons in 2 different files)
  3. Double entry check.SPS
  4. Find errors in 2 files (data entered twice).SPS
  5. Match one to many where key has 4 variables.sps
  6. Match 2 files using between-dates criteria.SPS
  7. Merge 2 data files based on many to many relationship.SPS
Top
  1. Coder Reliability with Nominal Data.SPS for version 14+ of SPSS
  2. with thanks to Pieter van Groenestijn. Here are related notes and references. Here are the syntax for version 13 and related notes
  3. Cohen's Kappa.SPS with thanks to Brian G. Dates. This syntax provides complete information on kappa for any number of raters and categories.
  4. Example that reads, writes, creates and transforms matrices.SPS
  5. Export variance covariance matrix to ASCII file.SPS
  6. Export variance covariance matrix to sav file.SPS
  7. Find inverse of a matrix.SPS
  8. Fuzzy Crosstable using Matrix command.pdf with thanks to Ruben P. Konig
  9. Hierarchical sort in MATRIX.SPS with thanks to Kirill Orlov
  10. Macro autogenerate initial data file.SPS with thanks to Fernando Cartwright
  11. Matrix out in.SPS
  12. Maximizing the trace of a matrix.SPS This is high powered stuff. Need to test all permutations of rows in order to find the one which maximizes the trace. For a 7*7 matrix (the maximum size this macro will handle), there are 5,040 permutations to test.
  13. Read matrix data.SPS
  14. Reliability analysis when input is a correlation matrix.SPS
  15. Transform a matrix into a vector.SPS

Top

  1. META-SPSS.ZIP An exhaustive set of syntax files written by Marta Garcia-Granero as well as sample data files and supporting documents. This is the Read Me First documentation.
  2. Meta Analysis: fixed and random effects models.SPS (With thanks to Valentim R. Alferes) This SPSS syntax does a meta-analysis on a set of studies comparing two independent means. It produces results for both fixed and random effects models, using Cohen's d statistics. The user has a total of 10 modes for entering summary data.

Top

  1. Count unique occurences of a multiple response.SPS
  2. Create dichotomous variables from multiple responses which are not in order.SPS
  3. Multiple responses are encoded as comma separated letters.SPS

Top

  1. Crosstab Chi-square and Phi in same table.SPS
  2. OMS and macros.SPS 

Top

  • Outliers
    Caution: Before replacing or deleting outliers, see the warning at the beginning of syntax # 3.
  1. Exclude cases over mean plus 2 times sd.SPS
  2. Replace outliers by average of cases with same characteristics.SPS
  3. Replace outliers by mean plus/minus n times sd.SPS
  4. Winsorize a mean.SPS

Top

  1. Extract bits from an integer.SPS 
  2. Extract portion of string.SPS (string contains first and last name, want first 3 letters of last name)
  3. Extract portion of string starting with a digit.SPS
  4. Extract Zip code from address field.SPS
  5. Extract two numbers from a string.SPS (e.g. string "120/90" becomes numbers 120 and 90)
  6. Flag if last characters of string are 'Esq'.SPS
  7. Parse a string into one letter per variable.SPS 
  8. Parse comma separated numbers.SPS
  9. Parse data separated by slashes.SPS
  10. Parse domain name from email addresses.SPS  
  11. Parse comma separated strings then autorecode results.SPS
  12. Parsing a variable which has embedded line feeds.SPS (thanks to Bjarte Aagnes)
  13. Remove letter at end of string and convert remaining string to a number.SPS
  14. Split a string variable into plaintiff and defendant portions.SPS
  15. String variable contains items separated by a slash.SPS (there is a variable number of items from one case to the next)
  16. Weed out letters in a string and create a number with remaining digits.SPS

Top

  1. Complex sampling without replacement.sps
  2. Draw without replacement (random permutation of numbers).sps
  3. Generate random phone numbers.sps (the syntax uses the following data file)
  4. Find random pairs of cases for T-test.sps
  5. Find random pairs of cases with same characteristics.sps
  6. Flag n random cases within each subgroups.SPS
  7. Get 2 independent samples meeting given criteria.sps
  8. Get 2 random samples same sex age education.sps
  9. Get n independent random samples of size m from same file.SPS
  10. Get random sample of x% of each stratum.SPS
  11. Get random sample of N cases from each stratum.SPS
  12. Getting repeated sampling from same file.sps
  13. List of random cases id 10 per line.SPS
  14. Match cases on basis of propensity scores.SPS (this involves matching cases which do not match but are close to each other)
  15. Proportional sampling without replace.sps
  16. Proportional random sampling.sps
  17. Proportional sampling without replacement.sps
  18. Random sample n males and n females.sps
  19. Random samples with same age sex education.sps
  20. Random split a file in two files.SPS
  21. Randomize a variable n times and keep each randomization.SPS
  22. Scramble social insurance numbers.sps
  23. Select 2 cases from each group.sps
  24. Select random samples of each group.sps
  25. Split files in 2 random portions.sps
  26. Split a file into 10 random groups of equal size.SPS
  27. Systematic fixed sampling.sps

Top

  1. Aggregating with the median.SPS
  2. Calculate cumulative sum of Var1.SPS
  3. Calculate mode.SPS
  4. Calculate number of distinct values within Case.SPS
  5. Calculate z scores across variables.SPS
  6. Code using percentiles of a subset.SPS
  7. Compute percentiles for one variable and by one or more grouping variables.SPS (with thanks to Tom Dierickx). Note that the percentiles end up in the data editor, not in the Output window.
  8. Compute percentages based on values of first case.SPS
  9. Create n tiles based on percent ranges rather than on count.SPS
  10. For each case, find the earliest case in the preceding 7 days.SPS (relatively complex stuff)
  11. Find 5 largest values within case.SPS
  12. Find last 2 scores on repeated measure.SPS
  13. Find multi-modal values per id.SPS 
  14. Identify the highest 3 scores of each case.SPS
  15. Identify variables having minimum value.SPS (with thanks to Maciek Lobinski)
  16. New variable equals cumulative totals by id.SPS
  17. Number consecutively cases with the same id.SPS
  18. Random order.SPS
  19. Rank equal intervals between minimum and maximum.SPS
  20. Rank on basis of percentage of good.SPS
  21. Rank variable names in alpha order.SPS
  22. Rank within cases.SPS
  23. Replace missing by median values within the case.SPS
  24. Round up to the higher point 5.SPS
  25. Saving confidence interval for mean (within groups).SPS
  26. Score a test with an answer key.SPS (thanks to A. Paul Beaulne)
  27. Sorting values within cases (using the bubble sort algorithm).SPS
  28. Syntax group data in bands.SPS
  29. Various Algorithms to sort within cases.SPSWith thanks to Kirill Orlov

Top


          Create

  1. Adding new cases using syntax.SPS
  2. Add variable equal to function of an existing Var.SPS
  3. A few simple examples of INPUT PROGRAM.SPS (a short tutorial)
  4. Copy some variables from each record type 1 to add a new record of type 0.SPS
  5. Create consecutive records at the end of the file.SPS
  6. Create constants for each non missing date.SPS
  7. Define new variables in empty data set.SPS
  8. Define varx to vary.SPS
  9. Duplicate cases n times where n is variable.SPS (see also Expand Crosstab Data below)
  10. Expand crosstab data into original data file.SPS (disaggregate data)
  11. Expand data x and y times.SPS eg from a case where age=20, males=5   and females=6 want to create 5 cases with age 20 and sex=1 and 6 cases where age=20 and sex=0
  12. Fill the gaps when Aggregate has empty categories.SPS  Syntax creates cases to fill the gaps
  13. Generate random dates.SPS
  14. INPUT program (to generate a random data file).SPS
  15. Insert missing cases (within id).SPS
  16. Insert missing dates (within id).SPS
  17. Printing date time in output.SPS

    Read
  18. Example of data list.SPS
  19. Example of INPUT program.SPS
  20. Read a variable number of records per case.SPS
  21. Read ASCII (logical case is made up of 5 rows of 10 cases).SPS
  22. Read ASCII file using FILE TYPE.SPS
  23. Read ASCII file using INPUT PROGRAM.SPS
  24. Read ASCII file with a forward slash delimiter.SPS
  25. Read ASCII file with comma or dash delimited data .SPS
  26. Read ASCII with comma and dot separated decimals.SPS
  27. Read ASCII file with comma separated data (within quotes).SPS
  28. Read ASCII file with fixed and free data.SPS
  29. Read ASCII file with FIXED Data.SPS
  30. Read ASCII file with REPEATING data.SPS
  31. Read comma delimited fields with commas inside quoted strings.SPS
  32. Read comments between the lines of data.SPS
  33. Read complex file.SPS
  34. Read data files that has no carriage returns.SPS (from AnswerNet) data is just one long stream, with no separation between records or fields, and no carriage returns
  35. Read data list free with consecutive commas.SPS
  36. Read data produced by CGI script.SPS
  37. Read data where each case has 4 numeric records and  a variable number of string records.SPS   (this is illustrates the use of the REREAD command)
  38. Read data inline File Type MIXED Records.SPS
  39. Read text file where n columns are to be ignored.SPS (n is a variable which varies by file)
  40. Skip first 6 Records.SPS
  41. Skip one line of data.SPS

    Write
  42. Write comma or tab delimited file.SPS
  43. Write frequency percentages to data file.SPS
  44. Write missing values as a dot.SPS
  45. Write special ASCII file.SPS
  46. Writing value labels instead of values.SPS

Top

  1. Add casewise regression coefficients to data file.SPS
  2. Breusch-Pagan & Koenker test.SPS (thanks to Marta Garcia-Granero)
  3. Calculate predicted values (unianova).sps
  4. Chow test.SPS
  5. Compare regression coefficients.SPS (thanks to A. Paul Beaulne for sending me this code)
  6. Compare coefficients generated by various groups.SPS
  7. Conditional logistic regression.SPS
  8. Do all univariate linear and logistic regressions.SPS (thanks to Marta Garcia-Granero)
  9. Do All-Subsets regressions.SPS  
  10. Generalized Estimation Equations (GEE).zip (thanks to Terry Duncan, PhD, Oregon Research Institute). GEE is a macro for analyzing longitudinal data. The SPSS macro uses the GEE approach of Liang and Zeger (1986) to model longitudinal data for a general class of outcome variables including gaussian, poisson, binary and gamma outcomes.
  11. Logistic regression by macro.SPS
  12. Multinominal Logistic Regression with split-sample validation.sps  (thanks to Maciek Lobinski for sending me this macro)
  13. Non linear regression (NLR) with variance of residuals as the loss function.SPS (this is not trivial)
  14. Piecewise regression.SPS (also known as "spline regression" and "piecewise polynomials")
  15. Regression calculates table of predicted values.SPS
  16. Regression in a loop.SPS
  17. Regression when holding out k cases.SPS
  18. Regression with correlation matrix as input.SPS
  19. Regression with normed weight.sps
  20. Repeated measures macro.SPS
  21. Ridge regression.SPS (this comes with SPSS)
  22. Testing individual regressors in logistic regression.SPS
  23. White's standard errors full OLS and White's SE output.SPS (thanks to Gwilym Pryce)
    See also the following related tutorials on Heteroscedasticity.
  24. White's test: calculate the statistics and its significance.SPS (thanks to Marta Garcia-Granero)

Top

  1. Delete cases with offset cases.SPS
  2. Delete double entries.SPS (thanks to Maciek Lobinski) For instance if, for a given case, var1 equals var2, the syntax replaces var2 by sysmis.
  3. Find duplicates.SPS
  4. Remove double quotes.SPS
  5. Remove duplicate records.SPS
  6. Remove unused variables from many files.SPS
  7. Replace consecutive spaces in string by a single space.SPS
  8. Replace character In string.SPS (see also String Manipulation Tutorial)
  9. Save duplicates in a separate file.SPS 

Top

  1. Allocate dummy variables to 24 hours.SPS
  2. Automated data transform from tall to wide.SPS 
  3. Automated restructure v4.SPS (thanks to Kevin Hynes) This example maintains a grouping factor while restructuring data from tall to wide.
  4. Automated restructure from long to wide.sps with thanks to Hillel Vardi. This is the sample data file used.
  5. Collapse empty variables within a case.SPS
  6. Deduplicate cases while keeping all the information.SPS (a cute little problem)
  7. Each variable occupies 5 rows of 10 columns.SPS (an other nice little problem)
  8. Find beginning and end of continuous periods.SPS
  9. From many to one example1.SPS
  10. From many to one example2.SPS
  11. From many to one with alpha data.SPS
  12. From many to one with specific order of new variables.SPS
  13. From one to Many simple.SPS
  14. From one to many with indicator variable.SPS
  15. Restructure data file example1.SPS
  16. Restructure data file example2.SPS
  17. Restructure data file example3.SPS
  18. Restructure data file example4.SPS
  19. Restructure from tall to wide (general solution).SPS (non trivial macro code...)
  20. Restructure time periods to a time matrix.SPS
  21. Restructure to calculate Kappa.SPS
  22. Transpose (FLIP) string variables.SPS
  23. Use former variable names as value labels.SPS

    Following examples require version 12 or above
  24. VarsToCases and CasesToVars.SPS

Top

  1. ROC curves & Youden's Index.SPS The syntax also computes Likelihood Ratios and Kullback-Leiber distances (requires v12 or above).

Top

  1. Power analysis examples.SPS  With thanks to Bruce Weaver
  2. Sample size for means.SPS With thanks to Marta Garcia-Granero. This is a collection of several short macros that perform sample size calculations for confidence interval estimation and one sample / two samples tests for means (this last one with equal or unequal sample sizes).
  3. Sample size for proportions.SPS With thanks to Marta Garcia-Granero. A collection of macros that perform sample size calculation for the estimation of one proportion and one or two samples hypothesis testing, as well as the calculation of the power of a test.
  4. Sample size for correlation hypothesis testing.SPS thanks to Marta!

Top

  1. Automated data transform from tall to wide.SPS
  2. Choice of include file depends on data.SPS
  3. End of macro DO LOOP comes from data.SPS
  4. Execute selective portions of syntax.SPS see also tips on INCLUDE command
  5. From 2 files to 1 cases per id.SPS
  6. Syntax varies based on name of data file.SPS

Top

  1. Are all words present.SPS This tests whether all words passed to the macro are present within a given string variable.
  2. Are all words present dichotomy vars.SPS Similar to above but creates one dichotomy variables for each target word 
  3. Change all strings in data file to lower case.SPS
  4. Convert numbers to strings.SPS
  5. Convert string '250 million' into a number.SPS (or '16 billion' etc)
  6. Convert string to numeric variable.SPS
  7. Soundex Phonetic Comparison.SPS

Top

  1. Show 95pc CI for failure points on a survival plot.SPS
  2. Survival Analysis Example.SPS
  1. Index of dissimilarity.SPS (formulas from Negroes in Cities (1965) by Karl and Alma Taeuber)
  2. Many tests of inequality v5.SPS   (this chart template is used by the syntax)

The above syntax (formulas come from poorcity.richcity.org ) calculates the following indexes:

   the ATKINSON index = DEMAND coefficient.
   the THEIL redundancy.
   the RESERVE coefficient.
   the D&R coefficient.
   the KULLBACK-LIEBLER redundancy.
   the HOOVER coefficient.
   the COULTER coefficient.
   the GINI coefficient.

The Lorenz curve is produced. The various indexes are plotted on the same graph when there is data for more than one year.  At the end, there are 9 examples about how to use the syntax.

Top

  1. Check for existence of file.SPS  
  2. Choice of include file depends on existence of a given variable.SPS
  3. Get all string or all numeric variables.SPS   (the 2 macros produced by this macro allow you to process all string or all numeric variables in the data file)

Top

  1. Gaussian Filter.sps 

Top

  1. Automatically rescale variable to be between 0 and 1.SPS
  2. Calculate utility of EuroQol 5D questionnaire.SPS  with thanks to AJ Garcia Ruiz
  3. Constrain a variable to a given interval.SPS(syntax is first given, then it is generalized using 2 macros)
  4. Convert numbers to string with leading zeros.SPS
  5. Create variable equal to z-scores of an existing variable.SPS
  6. Extract fist or first 2 digits of a large integer.SPS 
  7. Global autorecode.SPS A nice problem: Autorecode many string variables where the recode formula (eg a=1,b=2, etc) is the same for all variables even though none of the variables have all possible values
  8. Replace confidential information eg a ssn by a new (known) id.SPS 
  9. Replace values higher than n by the mean of the other values.SPS  
  10. Replace letter by 9999 then convert to number.sps
  11. Transform string coding into numbers.SPS (5A becomes 5.1; 7B becomes 7.2; 9D becomes 9.4  etc)
  12. zip code syntax.zip With thanks to Christopher Boyd. This zip file contains 2 syntax files: one recodes zip into town; the other does the reverse. Zip codes are those used by the US Census to generate zip code level employment data.

Top

  1. ANOVA A*B.SPS (thanks to Valentim Alferes) This does an A*B Factorial ANOVA and calculates variance components, measures of association, measures of effect size and observed power. Works with raw data or published summary statistics.
  2. ANOVA_Tables using 4 methods.SPS (thanks to Valentim Alferes) method 1:for Ns, Means and SDs; method 2 for Ns, Means and Variances; method 3 for Ns,Means and MS Error; method 4 for Means, Df num, Df den and MS Error.
  3. Cochran Hartley Critical Values.SPS This gives the tabulated critical values at 5% and 1% for both HOV tests. Thanks to Marta Garcia-Granero
  4. Compare mean of each hospital with mean of all other hospitals.sps (nice little macro)
  5. Do a T-Test with only the Means, SD and Ns.SPS (uses ANOVA)
  6. Do T-Test with only means,SD and Ns.SPS (thanks to Marta Garcia-Granero) this includes Hartley's F test, the standard T-test and Welch test, asymptotic and non asymptotic 95% CI are calculated.
  7. Hotelling's T**2 & Profile Analysis.SPS (thanks to Richard MacLennan)
  8. Multiple Mann-Whitney tests.SPS (using a macro to have a procedure inside a LOOP)
  9. ONEWAY with summary data1.SPS Performs a ONEWAY ANOVA plus several Homogeneity of Variances tests on summary data. Thanks to Marta Garcia-Granero
  10. ONEWAY with summary dataI2.SPS Performs several ONEWAY ANOVAS plus several Homogeneity of variances tests on summary data. Any number of variables can be analysed. Thanks to Marta Garcia-Granero.
  11. Standardized effects size (Cohen Glass and Hedges's d).SPS (with thanks to Marta) The effects size and their standard errors are added to the data file.
  12. T-Tests and Likert scales.SPS  
  13. T-Test effect size non overlap and power.txt
  14. (thanks to Valentim Alferes) User can either analyse raw data or reproduce the SPSS T-Test standard output using summary statistics in published articles.

Top

  1. Adjusted p-values algorithms.SPS thanks to Marta Garcia-Granero for this improved version of her code. References are included.
    The code calculates adjusted p-values using the following 8 methods:
    One-step: Bonferroni and Sidak,
    Step-down: Bonferroni (Holm's), Sidak (also called Holm's-Sidak) and Finner.
    Step-up: Hommel, Hochbeerg and Simes
  2. Calculate average percent score.SPS
  3. Calculations on dynamic columns.SPS
  4. Canonical correlation.sps (this comes with SPSS)
  5. Fill in the gaps.SPS (information in file has been left blank when it equals the information in the preceding case, this syntax fills the gap)
  6. Fill in the gaps (within ID).SPS
  7. Interaction in factorial designs when dependent variable is not normal.SPS Thanks to Marta Garcia-Granero for this code.
  8. Stop or resume generating outputs in the output window.SPS

Top

  1. Combine many data files with same variables.SPS
    alternative 1: the following script works even when file names are unknown
    alternative 2: Use the DOS command copy *.txt newfile.txt to combine all txt files in the folder (thanks to Scott Clark for this suggestion)
  2. Combine any number of consecutively named sav files 50 at a time.SPS
  3. Combine many xls files into a single sav file.SPS
  4. Combine 2 data files many to many.SPS
  5. Data list is outside the main syntax.SPS (illustrates how a syntax file can be modified by syntax)
  6. Delete cases contained in file2 from the main data file.SPS
  7. Erase files.SPS
  8. Example 1 using UPDATE command.SPS
  9. Example 2 using UPDATE command.SPS
  10. Get mean from 3 different files.SPS
  11. Include 200 syntax files by macro.SPS
  12. Keep only cases from Master file whose id are in second file.SPS
  13. Macro to delete a list of files.SPS 
  14. Many folders and many files.SPS
  15. Process all xls files in folder.sbs (this scripts works jointly with this syntax file)
  16. Run a macro on several files.SPS
  17. Run syntax on files whose names are derived from a data file.SPS
  18. Run a macro on every file whose name is in a sav file.txt
  19. Save file1 file2 file3 etc by macro.SPS
  20. Split big files into separate categories.SPS (create a different sav file for each value of a numeric categorical variable)
  21. Split big files into separate categories string var.SPS (create a different sav file for each value of a string categorical variable)
  22. Split file with kn cases into k files of n cases each.SPS
  23. Unusual file merge.SPS
  24. Show number of differences, if any, between 2 files.SPS (to check double entry of data). For additional examples, see Matching data files

Top

  1. Conditionally replacing missing by mean.SPS
  2. Conditionally replacing missing by mean example 2.SPS
  3. Delete variables that have only missing values.SPS
  4. Identifying the 3 types of missing values.SPS
  5. Hot Deck.SPS substitution of missing values of X within STRATUM (thanks to Theo van der Weegen)
  6. List variable names with missing values and identify main elements of cases.SPS
  7. Listing Variables with missing values (Per case).SPS with thanks to David Marso
  8. Mean substitution in additive scale.SPS
  9. Missing values and DO IF.sps
  10. Recode certain dates as missing.SPS
  11. Replace "Blanks" by value from preceding case.SPS
  12. Replace missing by mean of category.SPS
  13. Replace missing by median values within each case.SPS
  14. Replace missing by random value taken from cases with valid value.SPS (see Hot Deck.SPS above  for a more general solution)
  15. Replace missing with mean.SPS

 

 

Top of page

 

 

Syntax
Home FAQ Syntax Macros Scripts Python Tips Links

 

SPSS Tutorials
Learning Syntax
Debugging Syntax
Standard data files


 

Keywords:


powered by
FreeFind

 

Site Map
Feedback



Other
languages

Deutsch
EspaŮol
Francais
Italiano
PortuguÍs
Russian

Do you love this site?

This page was last updated on  2012/03/31        Raynald's SPSS Tools

© Raynald Levesque 2001-12