Keyboard shortcuts

Press ← or → to navigate between chapters

Press S or / to search in the book

Press ? to show this help

Press Esc to hide this help

简介

Statscraft 0.61.0, release v0.61.0

Statscraft

Statscraft 是一款面向社会科学的免费开源统计软件,从第一行代码起就为 AI 智能体而设计。它读取 .sav 文件,运行您现有的语法,支持 Windows、macOS 和 Linux。两个用 Rust 编写的程序共用一个引擎:命令行程序 statscraft 和桌面窗口程序 statscraft-gui。

下载 · 文档 · 网站

安装

从下载页面下载适合您系统的安装包;每个安装包都包含窗口程序和命令行。

  • Windows: 运行 setup.exe。它只为您的用户安装,不需要管理员权限。另外也提供不带安装程序的 .zip。
  • macOS: 解压 .tar.gz,然后把 Statscraft.app 拖到“应用程序”文件夹。首次启动时,请在 System Settings > Privacy & Security 中允许它运行。
  • Debian 和 Ubuntu: sudo apt install ./statscraft_X_amd64.deb
  • 其他 Linux: 将 .tar.gz 解压到 ~/.local(具体步骤)。

On Linux the programs need glibc 2.39 or newer: Ubuntu 24.04, Debian 13 or Fedora 40, or any later version. On an older system, build from source.

Then open Statscraft from your applications menu, or check the command line with statscraft --version. To try it on invented data, use the sample file in docs/sample and follow Getting started. Install and update has every step, uninstalling and updates.

为什么与 AI 智能体一起使用

  • 一切都是语法。 智能体编写的是您可以阅读、保存、再次运行和分享的命令,而不是没有人能重现的点击操作。
  • 智能体能读懂的结果。 每个结果都以 JSON 返回,附带原始数值;出错时会指出所在的行和列,通常还会给出提示。
  • 小步推进。 会话在多次运行之间保留数据,因此智能体可以分步工作。检查在副本上运行,不写入任何内容;运行失败时也不会改变任何内容。
  • 您可以随时查看并掌控一切。 智能体的操作会实时显示在窗口中,Undo 可以撤销一步。

运行一次 statscraft connect,即可将 Statscraft 添加到您计算机上的 AI 智能体中。面向 AI 智能体的 Statscraft 说明智能体应如何工作,连接您的 AI 智能体 说明该命令会更改哪些内容。

功能

  • 数据文件。 读写 .sav 和 .zsav 文件,保留标签、缺失值和多重响应集。可以打开 Excel 工作簿和文本文件,并写出 Excel、CSV 和 Stata 文件。
  • 数据准备。 计算、重新编码、筛选、加权、汇总、合并和重构数据,支持宏和矩阵语言。
  • 自定义表格。 按组统计计数、百分比和均值,支持总计、小计、多重响应集,以及用字母标注的显著性检验。
  • 统计分析。 频数、交叉表、均值、t 检验和方差分析;线性回归、逻辑回归及其他多种回归;一般线性模型、广义线性模型和混合线性模型;因子分析、聚类分析和决策树分析;生存分析、预测、复杂抽样、贝叶斯检验和功效分析。
  • 输出。 表格和图表可导出到 Excel、Word、PowerPoint、PDF 和网页。图表在办公软件中仍是可编辑的图表。
  • AI 智能体。 提供 MCP 服务器、JSON 输出、在多次运行之间保留数据的会话,以及标明行号和列号的错误信息,让智能体完成分析,您在窗口中查看过程。

命令页面列出了全部命令。

Statscraft 是一个独立项目,与其他统计软件的开发商及 ArtCraft 套件均无关联,也未获得其认可。产品名称是其各自所有者的商标。

状态:早期开发阶段。采用 MIT 许可证。

Statscraft 0.61.0, release v0.61.0

入门

本页带您从安装 Statscraft 开始,直到得到一个含自定义表格的 Excel 工作簿。您在窗口中操作,使用下面下载的示例文件。最后,您会看到在命令行上完成同样的工作。

安装

从下载页面下载适合您系统的安装包。每个安装包都包含两个程序:窗口程序和 statscraft 命令行。

Windows。 运行 statscraft-X-windows-x86_64-setup.exe(X 为版本号)。它只为您的用户安装,无需管理员权限,并把 Statscraft 添加到“开始”菜单。如果 Windows 提示发布者未知,请选择 More info,然后选择 Run anyway。

macOS。 双击 statscraft-X-macos-universal.tar.gz 将其解压,然后把 Statscraft.app 拖到 Applications。第一次打开时,macOS 会提示无法验证该应用:点击 Done,然后打开 System Settings > Privacy & Security,在关于 Statscraft 的提示旁点击 Open Anyway。

Debian 和 Ubuntu。 使用 sudo apt install ./statscraft_X_amd64.deb 安装软件包。之后 Statscraft 会出现在应用程序菜单中。它需要 Ubuntu 24.04 或 Debian 13,或更新的版本。

其他 Linux。 将 tarball 解压到 ~/.local:先运行 mkdir -p ~/.local,再运行 tar -xzf statscraft-X-linux-x86_64.tar.gz --strip-components=1 -C ~/.local。这些程序需要 glibc 2.39 或更新版本(例如 Fedora 40)。

安装与更新介绍了详细内容:Windows 便携版、macOS 上的命令行、如何卸载以及更新方式。

打开示例文件

下载示例文件 survey.sav。这是一份虚构的客户调查,共 300 名受访者,每个变量和值都带有标签。

  1. 启动 Statscraft。一个空的数据窗口随即打开。
  2. 选择 File > Open data…,然后选取 survey.sav。

数据窗口现在显示各个个案,每位受访者一行。网格上方的 Show value labels 用于在编码值和对应标签之间切换。

查看变量

点击 Variables 选项卡。每一行是一个变量,包括其标签、值标签和缺失值。本页使用以下变量:

Variable内容
regionNorth、South、East 或 West
satisfaction总体满意度,从 1(非常不满意)到 5(非常满意);9 表示“Don’t know”,为缺失值
ch_web to ch_email五个是/否变量,每个对应客户使用过的一种渠道

这五个渠道变量还构成一个多重响应集 $channels:即允许多个答案的一道题。Data > Define Multiple Response Sets… 中可以看到它。

双击标签即可修改。每次修改都会运行一条简短的命令,Statscraft 由此记录您的工作(详见下文)。

制作频数表

  1. 选择 Analyze > Descriptive Statistics > Frequencies…。
  2. 在变量列表中点击 region,然后点击 Variables 旁边的 Add。
  3. 点击 OK。

输出窗口随即打开,显示如下表格:

RegionFrequencyPercentValid PercentCumulative Percent
North7525.025.025.0
South6220.720.745.7
East8127.027.072.7
West8227.327.3100.0
Total300100.0

输出下方的日志显示了生成该表格的命令:FREQUENCIES VARIABLES=region.

创建自定义表格

自定义表格将多个问题并排显示,并标出具有统计显著性的差异。本例按地区显示满意度和使用过的渠道。

  1. 选择 Analyze > Custom Tables…。
  2. 在左侧列表中,点击 satisfaction,以及 Multiple response sets 下的 $channels (set)。然后点击 Rows 旁边的 Add。
  3. 点击 region,然后点击 Columns 旁边的 Add。
  4. 在 Summaries 下,取消勾选 Count,并勾选 Column %。
  5. 在 Significance tests 下,勾选 Compare column proportions。
  6. 在 Letters of the column comparisons 下,选择 In the main table, column keys。
  7. 点击 OK。

输出窗口显示该表格。每个地区有一列百分比,旁边还有一列字母:

North(a)South(b)East(c)West(d)
Overall satisfaction with the service
Very dissatisfied4.3%6.9%15.1%d2.6%
Dissatisfied20.0%8.6%34.2%b28.9%b
Neutral15.7%32.8%35.6%a38.2%a
Satisfied37.1%c d27.6%12.3%15.8%
Very satisfied22.9%c24.1%c2.7%14.5%
Channels used
Website70.0%71.2%78.8%76.3%
Mobile app24.3%27.1%31.3%36.8%
Phone37.1%59.3%56.3%56.6%
Store22.9%23.7%23.8%21.1%
Email45.7%44.1%33.8%35.5%

每个地区都有一个键:a 代表 North,b 代表 South,c 代表 East,d 代表 West。百分比旁的字母表示该百分比显著高于对应键所代表地区的百分比。例如,37.1% 旁的“c d”表示 North 地区感到满意的客户多于 East 或 West 地区。表格下方的注释说明所用的检验。自定义表格完整介绍了该对话框。

导出到 Excel

  1. 选择 File > Export…。
  2. 在 Format 下,选择 Excel workbook (.xlsx),并选择 One sheet per table 或 All tables on one sheet。
  3. 点击 Export…,然后选择工作簿的保存位置。

每个表格在 Excel 中都保留其布局。数字仍然是数字,您可以用它们计算;显著性字母作为文本留在数字旁边。导出到 Excel列出了所有选项。

保存语法

您所做的一切都是以语法运行的,也就是 Statscraft 语言的命令。您可以保存这些语法,以后再次运行,用于这个文件或下个月的数据。

  1. 查看输出下方的日志。
  2. 点击 Copy syntax。这会复制您会话中的所有命令。
  3. 选择 File > New > Syntax,按 Ctrl+V 粘贴,然后选择 File > Save syntax as…。将其保存为 first-table.sps。

文件内容如下(您的 GET FILE 行包含您文件的完整路径):

GET FILE='C:\Users\anna\Documents\survey.sav'.
DATASET NAME DataSet1.
FREQUENCIES VARIABLES=region.
CTABLES
  /TABLE satisfaction [C] [COLPCT.COUNT PCT40.1] + $channels [COLPCT.COUNT PCT40.1] BY region [C]
  /COMPARETEST TYPE=PROP ALPHA=0.05 ADJUST=BONFERRONI MERGE=YES STYLE=SIMPLE.

要再次运行,用 File > Open syntax… 打开它,然后点击 Run all。除了 OK,每个对话框还有 Paste,它把对话框的语法放入语法窗口而不运行。

在命令行上完成同样的工作

statscraft 命令行无需窗口即可运行同样的语法。在终端中,进入存放 survey.sav 和 first-table.sps 的文件夹:

statscraft describe survey.sav
statscraft run first-table.sps --xlsx tables.xlsx

describe 列出变量。run 以文本形式打印每个表格,同时将它们写入 tables.xlsx。命令行介绍了所有选项。

与 AI 智能体协作

AI 智能体可以替您完成同样的步骤:查看变量、编写语法、运行语法并读取结果。在窗口中通过 Edit > Settings > AI agents 连接一次您的智能体即可。连接您的 AI 智能体说明了具体方法,面向 AI 智能体的 Statscraft说明了智能体如何使用 Statscraft。

下一步

  • 窗口:数据窗口、语法窗口和输出窗口,以及所有菜单。
  • 命令:每个命令一页,包含其语法和一个示例。
  • 命令行:所有子命令和选项。

Statscraft 0.61.0, release v0.61.0

安装与更新

Statscraft 可在 Windows、macOS 和 Linux 上运行。每个安装包都包含两个程序:窗口程序(statscraft-gui)和命令行程序(statscraft)。

下载

请从下载页面下载适合您系统的安装包。文件名中的 X 代表版本号:

文件 {#file}适用于
statscraft-X-windows-x86_64-setup.exeWindows,带安装程序
statscraft-X-windows-x86_64.zipWindows,不带安装程序
statscraft-X-macos-universal.tar.gzmacOS,适用于 Apple 芯片和 Intel 芯片
statscraft_X_amd64.debDebian 和 Ubuntu {#debian-and-ubuntu}
statscraft-X-linux-x86_64.tar.gz其他 Linux 发行版

下载页面还说明了如何用已发布的校验和核对文件。供 AI 智能体使用的文件见连接您的 AI 智能体。

Windows

运行 statscraft-X-windows-x86_64-setup.exe。它只为当前用户安装,不需要管理员权限。

  • “开始”菜单中会出现 Statscraft,点击即可打开窗口。
  • 安装后打开的任何终端中都可以使用 statscraft。
  • .sav 和 .zsav 文件在窗口中打开,.sps 文件在其语法编辑器中打开。如果已有其他程序打开这些类型的文件,它仍是默认程序,Statscraft 会出现在 Open with 中供选择。

如果 Windows 提示安装程序来自未知发布者,请选择 More info,然后选择 Run anyway。

要卸载,请打开 Settings > Apps > Installed apps,找到 Statscraft 并选择 Uninstall。

不使用安装程序的 Windows

在不允许安装程序的电脑上,请使用 .zip 文件。把它解压到任何可写入的位置,例如“文档”中的某个文件夹或 U 盘(在资源管理器中:右键单击,Extract All)。文件夹中包含:

  • statscraft-gui.exe,即窗口程序:双击即可启动 Statscraft;
  • statscraft.exe,即命令行程序:在终端中从该文件夹运行,或将该文件夹添加到 PATH;
  • LICENSE.txt 和 README.md。

这种方式没有“开始”菜单项,双击文件也不会打开。请用 File > Open data… 打开文件,或把文件拖到 statscraft-gui.exe 上。请将 LICENSE.txt 与程序放在一起,以便更新时知道安装位置。要删除 Statscraft,删除该文件夹即可。

macOS

在 Finder 中双击 statscraft-X-macos-universal.tar.gz 将其解压。把 Statscraft.app 拖到 Applications。

第一次打开时,macOS 会提示无法验证该应用。请点击 Done(不要点 Move to Trash),然后:

  1. 选择苹果菜单 > System Settings,然后选择 Privacy & Security。
  2. 在 Security 下找到关于 Statscraft 的提示,点击 Open Anyway。
  3. 输入您的登录密码,然后点击 OK。

此后,Statscraft 和其他应用一样双击即可打开。对于 .sav、.zsav 和 .sps 文件,Finder 会在 Open With 中提供 Statscraft。

命令行程序是同一文件夹中的 statscraft 文件。请将它移到 PATH 中的某个文件夹,例如:

mkdir -p ~/.local/bin
mv ~/Downloads/statscraft-X-macos-universal/statscraft ~/.local/bin/

如果 ~/.local/bin 还不在 PATH 中,请在 ~/.zshrc 中加入 export PATH="$HOME/.local/bin:$PATH"。第一次运行 statscraft --version 时会像应用一样被阻止:请在 Privacy & Security 中允许它,然后再运行一次。

要卸载,请把 Statscraft.app 移到废纸篓,并删除 statscraft 文件。

Debian 和 Ubuntu

sudo apt install ./statscraft_X_amd64.deb

该安装包需要 Ubuntu 24.04 或 Debian 13,或更新的版本(glibc 2.39 或更新版本)。在较旧的系统上,apt 会因 libc6 依赖无法满足而停止;请在该系统上从源代码构建 Statscraft。

之后 Statscraft 会出现在应用程序菜单中,.sav、.zsav 和 .sps 文件会在窗口中打开。要卸载,请运行 sudo apt remove statscraft。

其他 Linux 发行版

tarball 中包含 bin 和 share 两个文件夹。这些程序需要 glibc 2.39 或更新版本(Ubuntu 24.04、Debian 13、Fedora 40 或任何更新的版本);在较旧的系统上会提示找不到 GLIBC_2.39,这时需要从源代码构建 Statscraft。将 tarball 解压到 ~/.local,然后刷新文件类型和应用程序菜单:

mkdir -p ~/.local
tar -xzf statscraft-X-linux-x86_64.tar.gz --strip-components=1 -C ~/.local
update-mime-database ~/.local/share/mime
update-desktop-database ~/.local/share/applications

如果没有 update-desktop-database,请跳过那一行。~/.local/bin 必须在您的 PATH 中;在大多数发行版上,只要该文件夹存在就会如此。如果您刚刚创建了这个文件夹,请注销后重新登录;在此之前,请用完整路径运行 ~/.local/bin/statscraft --version。

要卸载,请删除该 tar 包放入的内容:

cd ~/.local
rm bin/statscraft bin/statscraft-gui share/applications/statscraft.desktop share/mime/packages/statscraft.xml
rm share/icons/hicolor/*/apps/statscraft.png share/icons/hicolor/scalable/apps/statscraft.svg
rm -r share/doc/statscraft
update-mime-database ~/.local/share/mime

更新

有新版本时,窗口会在菜单下方显示一个提示栏。Update now 安装新版本,Later 隐藏提示栏直到下次检查。Help > Check for updates 立即检查。

Update now 的具体操作取决于您安装 Statscraft 的方式:

安装方式结果
Windows 安装程序窗口会询问未保存的工作,然后关闭,安装新版本并重新打开。
Windows .zip文件夹中的两个程序被替换。Restart now 打开新版本。
Linux tar 包~/.local/bin 中的两个程序被替换。Restart now 打开新版本。
.deb 安装包新安装包保存在 ~/Downloads 中,系统会要求您输入密码进行安装。然后点击 Restart now。
macOS提示栏中有一个 Download 链接。解压新安装包,用新的 Statscraft.app(以及 statscraft 文件)替换旧的。首次启动时需要再次点击 Open Anyway。

每个下载的文件在使用前都会与该版本发布的校验和进行核对。

窗口每天最多检查一次。检查时不会发送任何关于您或您数据的信息。要关闭检查,请取消勾选 Edit > Settings > Updates > Check for updates automatically。

在命令行中:

statscraft update --check     is there a newer version?
statscraft update             install it

在 Debian 和 Ubuntu 上,statscraft update 会下载安装包,并打印出安装它所需的那一条命令。在 macOS 上,它会给出下载页面。命令行页面列出了各个选项。

Statscraft 0.61.0, release v0.61.0

窗口

本页面向在 Statscraft 窗口中工作的分析人员:数据编辑器、语法编辑器和输出,以及它们的菜单和对话框。入门将带您制作第一张表格。

窗口程序(statscraft-gui)与命令行使用同一个引擎。它有三类窗口,全部共用一个会话:

  • 每个打开的数据集各有一个数据窗口,带有 Data 和 Variables 两个标签页;
  • 每个语法文件各有一个语法窗口;
  • 每个输出文档各有一个输出窗口。

会话中有一个活动数据集,任何窗口中的每条命令都作用于它。窗口中的每项更改和每个结果都来自语法(参见语法是唯一的命令层)。

不带文件启动时,程序会打开一个空的数据窗口,供您从中打开文件。

打开文件

  • 在终端中,statscraft-gui survey.sav job.sps 会打开一个数据文件和一个语法文件。两者都是可选的。
  • File > Open data 会立即在单独的数据窗口中打开 .sav 或 .zsav 文件。空的数据窗口会接收第一个文件。
  • Excel 工作簿(.xlsx、.xlsm、.xls)或文本文件(.csv、.txt、.tab、.dat)会先打开 Open Data 对话框。它写出 GET DATA,并像 .sav 文件一样在其后写出 DATASET NAME:
    • 对于工作簿:工作表、第一行是否为变量名,以及一个范围,例如 A1:F200(留空则读取整个工作表);
    • 对于文本文件:分隔符(逗号、分号或制表符;自动选择第一行中出现最多的那一个),以及第一行是否为变量名,并显示该行。每个变量都以 AUTO 方式读取。
  • 通过 Open Data 运行后,File > Save data 会要求指定一个新的 .sav 文件。
  • File > Open output 会运行 OUTPUT OPEN FILE='...'.,在单独的输出窗口中打开 Statscraft 输出文件(.scout)。参见保存输出。
  • File > Recent files 列出最近打开或保存的十个文件。
  • 从文件管理器拖放到窗口上的文件也会打开。.sav 或 .zsav 文件作为数据打开,工作簿或文本文件在 Open Data 对话框中打开,.sps 文件在语法窗口中打开,每个 .scout 文件在输出窗口中打开。一次只打开一个数据文件和一个语法文件;状态栏会列出未打开的文件。
  • Windows 上的安装程序以及 macOS 和 Linux 的安装包,使您双击 .sav、.zsav、.sps 或 .scout 文件即可在 Statscraft 中打开它。如果 Statscraft 已在运行,文件会在该窗口及其会话中打开,并且窗口会切换到最前面;从菜单启动 Statscraft 而不带文件时,仍会打开一个新窗口。

导出数据

File > Export data 写出 SAVE TRANSLATE。所选文件名决定文件类型:Excel 工作簿(.xlsx)、CSV 文件(.csv)、制表符分隔的文本(.txt)或 Stata 文件(.dta)。对话框提供:

  • 第一行为变量名、变量标签或不设;
  • 用值标签代替值;
  • 将用户缺失值写为空;
  • 要导出的变量(未选择时:全部变量,按数据集中的顺序);
  • 对于 Stata 文件,取代第一行和值标签选项的是:读取该文件的 Stata 版本(8 到 14,默认 14)以及完整字符串(EDITION=SE,默认开启;关闭时,字符串在 80 字节处截断)。值标签以 Stata 值标签的形式写入文件。

文件对话框询问后,已存在的文件会被替换。

数据窗口

会话中每个含有数据的数据集都有一个数据窗口。标题显示文件和数据集名称,例如 survey.sav [DataSet1],活动数据集的窗口会标明 (active)。

  • 打开数据文件会打开它的窗口。从窗口中打开的文件会获得下一个可用的数据集名称(DataSet1、DataSet2 等),因此之前打开的数据仍保持打开。
  • 由语法创建的数据集也会获得窗口:DATASET COPY、命令已向其写入数据的 DATASET DECLARE,以及在语法中输入的不带 DATASET NAME 的 GET。被 DATASET CLOSE 关闭的数据集会失去其窗口,而 DATASET NAME 会让窗口以新名称保留。
  • 在数据窗口中的任何位置单击(包括其菜单),都会使其数据集成为活动数据集。这会运行 DATASET ACTIVATE name.,并像其他运行一样显示在日志中。在活动数据集的窗口中单击不会运行任何命令。
  • 从数据窗口打开的对话框作用于该窗口的数据集,此时它已是活动数据集。
  • 每个窗口都保留自己的标签页、选择范围和查找栏。网格编辑、右键菜单和 Delete 键在每个数据窗口中都可使用。
  • 在语法中输入的不带 DATASET NAME 的 GET 所读取的数据没有名称。当另一个数据集成为活动数据集时(在另一个数据窗口中单击、使用 Active 列表、打开文件),这样的数据集会被关闭。如果它有未保存的更改,会先弹出询问:Save 保存后继续,Don’t save 不保存直接继续,Cancel 保持一切不变。
  • File > Close 或窗口的关闭按钮会关闭该数据集。如果其数据未保存,会弹出询问,提供 Save、Don’t save 和 Cancel。关闭时运行 DATASET CLOSE name.。如果该数据集是活动数据集,会先激活另一个打开的数据集,因为对活动数据集运行 DATASET CLOSE 只会去掉它的名称;如果它是最后一个数据集,随后会运行 NEW FILE.。
  • 当其他窗口仍打开时,关闭最后一个数据窗口不会退出程序。再次打开文件会重新打开数据窗口。
  • File > New > Data 会运行 NEW FILE.,并在 Variables 标签页上打开一个空的数据窗口。之前打开的数据仍在自己的窗口中打开;没有名称的活动数据会先得到一个名称(DATASET NAME DataSet2. 等)。在 Variables 标签页中命名的第一个变量会以下一个可用名称开始新的数据集(NUMERIC height (F8.2). 和 DATASET NAME DataSet3.),因此它会像从窗口打开的文件一样保持打开。

Data 标签页

个案显示在一个只绘制可见单元格的网格中。

网格显示的内容

  • 网格上方的 Show value labels 用于开启和关闭值标签显示。
  • 每一列按变量的对齐方式绘制值和标签。如果文件中未设置对齐方式,数字靠右,字符串靠左。
  • 超出列宽的值或标签会以省略号截短,并保持其对齐方式。
  • 系统缺失值显示为一个灰色小圆点。空字符串不显示任何内容。
  • 当 FILTER BY 生效时,被过滤器排除的每个个案的行号上会有一条斜线。该个案仍留在网格中。
  • 列宽等于变量的显示宽度(.sav 文件为每个变量保存的宽度)。拖动变量名右侧的边框即可更改。这会运行 VARIABLE WIDTH var (n).,因此宽度会随数据一起保存。

编辑

  • 双击单元格或按 Enter 键即可修改。Enter 确认,Escape 取消。
  • 最后一个个案下方的空行用于添加新个案:在那里输入一个值会运行 ADD CASE.,然后像任何编辑一样设置该值。在您输入之前,新个案的其他值都是缺失值。
  • 选中整列时按 Delete,会询问是否删除这些变量。
  • 选中单元格时按 Delete 会清除它们,例如 IF (RANGE($CASENUM, 2, 4)) age = $SYSMIS.(字符串则为空白)。Ctrl+Z 可以恢复。

按键与选择

  • 方向键、Page Up 和 Page Down、Home 和 End 用于移动选择。
  • Ctrl 加方向键跳到第一行或最后一行、第一列或最后一列。Ctrl+Home 和 Ctrl+End 跳到第一个和最后一个单元格。
  • Tab 和 Shift+Tab 移到下一个和上一个单元格,并顺带确认正在进行的编辑。
  • Shift 加这些按键,或 Shift+单击,可将选择扩展为一个区块。
  • 单击行号或列名会选中整个个案或变量。Shift+单击选择一个范围,Ctrl+单击添加或移除一个。
  • 在单元格上拖动会选中该区块。在列名或行号上拖动会选中其间的变量或个案。
  • Ctrl+C 将所选内容复制为制表符分隔的文本,第一行为变量名,可粘贴到电子表格或文本编辑器中。单个单元格只复制其文本。超过两百万个单元格时不会复制。
  • Ctrl+V 或单元格菜单中的 Paste 会把剪贴板中以制表符分隔的文本,从选中的单元格开始放入各单元格。每个单元格都按您手动输入的方式读取;粘贴到最后一个个案之下时会添加所需的个案;按一次 Ctrl+Z 即可撤销整个粘贴。如果某个单元格不符合其变量,粘贴会停止,状态栏会指出它所在的行和变量。一次粘贴最多 200,000 个单元格,在个案非常多的文件中会更少。
  • 填充柄:选中单元格右下角的小方块。把它向下、向上、向右或向左拖过更多单元格(在数据已有的个案和变量范围内),选区就会延续到这些单元格上。按相同步长变化的数字会延续数列(1、2、3 会继续为 4、5;相隔一天的日期会按天继续),单个数字或其他单元格则会重复填充。这相当于粘贴这些值:每个单元格都按您手动输入的方式读取,只要有一个单元格不符合其变量,整个填充就会停止,按一次 Ctrl+Z 即可撤销。把填充柄拖到单元格下方或上方并按住,网格会继续滚动,指针离得越远滚动越快,因此填充可以到达屏幕外很远的个案;拖动选择时也会这样滚动,沿列标题(横向)或行号(纵向)拖动以选择列或行时也是如此。用语法实现同样的操作,例如让 x 的第 5 到第 20 个个案从 3 开始、步长为 2:IF ($CASENUM >= 5 AND $CASENUM <= 20) x = 3 + ($CASENUM - 4) * 2.

Variables 标签页

每个变量一行,包含以下列:名称、类型、格式、宽度、小数位、标签、值标签、缺失值、列宽(显示宽度,与 Data 标签页中显示的宽度相同)、对齐方式、测量级别和角色。文件中未设置对齐方式或角色的变量,数字靠右、字符串靠左,角色为 Input。

最后一个变量下方的空行用于新建变量:在其 Name 字段中输入名称并按 Enter。这会运行 NUMERIC name (F8.2).,该变量放在最后;像其他变量一样,在它的行中更改类型、标签等。空的数据窗口也有这一行,因此不带文件启动程序,或使用 File > New > Data 后,可以立即添加变量。

修改字段

双击字段即可修改,或按 Enter 键修改光标所在的字段。

  • 类型和格式。 类型(Numeric、Date 或 String)和格式会打开一个小对话框。它只提供实际存在的格式:数字(普通、逗号、点、美元、百分比、科学计数、前导零)、日期和时间,以及字符串。宽度和小数位是该格式限制范围内的数字。对话框运行 FORMATS,如果是新类型或新的字符串宽度则运行 ALTER TYPE。更改类型会丢弃值标签和缺失值,对话框会对此作出提示。
  • 值标签。 一个编辑器,每个代码和标签占一行,可以修改、添加和删除。它用完整的标签集运行 VALUE LABELS。
  • 值标签编辑器中的 Paste many 是一个可输入多行的文本区域,每行一个代码和一个标签。二者以制表符、分号、等号或逗号分隔(取文本中最先出现的那一种)。它可以更新标签集(ADD VALUE LABELS:添加新代码,修改已有代码的标签),也可以替换标签集(VALUE LABELS)。
  • 缺失值。 一个编辑器,最多可设三个值;对于数字,可设一个范围再加一个值(LO 和 HI 分别表示最小值和最大值)。它运行 MISSING VALUES。
  • 当该变量的行是多个选中行之一时,值标签和缺失值编辑器可以将相同的标签或缺失值赋给其他选中的同类型变量。
  • Columns 运行 VARIABLE WIDTH,alignment 运行 VARIABLE ALIGNMENT,role 运行 VARIABLE ROLE。对齐方式和角色与测量级别一样,从列表中选择。

按键与选择

  • 按键、鼠标选择和 Ctrl+C 的用法与 Data 标签页相同。
  • Delete 会在询问后用 DELETE VARIABLES 删除行号被选中的变量。Edit > Undo 可以恢复它们。
  • 拖动列边框可调整列宽。这些宽度属于窗口设置。

查找变量

在 Data 或 Variables 标签页中按 Ctrl+F 会打开查找栏。

  • 输入文字后,会跳到名称或标签中包含该文字的第一个变量,不区分大小写。
  • Enter 或 F3 跳到下一个。Escape 关闭查找栏。
  • 在 Variables 标签页中跳到该变量的行,在 Data 标签页中跳到它的列。

右键菜单

右键单击会针对所点击的对象打开一个菜单。菜单顶部显示它作用的对象。

  • 在列名上,或在选中的列内单击时作用于所有选中的列:
    • 按这些列升序或降序排序(SORT CASES)。
    • Frequencies 或 Descriptives(仅限数值变量),立即运行。
    • Rename(重命名)。
    • Insert variable before:插入一个新的数值变量 new_1。
    • Filter by values…:列出该变量的不同值及其计数(最多 2,000 个),并提供一个搜索框和每个值的复选框;Check shown 和 Uncheck shown 作用于搜索显示的值。OK 通过一个过滤变量保留带有已勾选值的个案,因此不会删除任何个案,例如 COMPUTE filter_$ = (ANY(region, 'north', 'east')). 然后 FILTER BY filter_$.。在命令行或 MCP 中,FREQUENCIES 给出相同的值和计数列表,语法也相同。
    • Change to numeric,适用于所有值都是普通数字的字符串列(这样的列在名称后显示 (123)):运行 ALTER TYPE,使用能容纳所有值的格式,空白值变为缺失值。按 Ctrl+Z 可恢复为文本。在命令行和 MCP 中,这些列在 describe 中带有 numbers_as_text。
    • Copy、Paste(从第一列的第一个个案开始)、Delete。
  • 在单元格上:
    • Copy、Paste、Edit、Clear value。
    • Only cases where the variable has this value:一个将其他个案排除在分析之外的过滤器(FILTER BY)。它比较的是存储的值,而不是显示的四舍五入值。
    • Stop filtering(停止过滤)。
    • Keep only cases where…:打开 Select Cases,以删除其他个案。
    • 按该变量升序或降序排序。
  • 在行号上:Copy、Paste(从第一个个案的第一个变量开始)或 Delete case。
  • 在 Variables 标签页中,行号上的菜单与列名上的菜单相同,只是没有 Paste。在单元格上,菜单以该字段的 Edit 开头。

菜单项的行为:

  • 每个菜单项都像其他运行一样运行语法,因此会显示在日志中,并且可以用 Ctrl+Z 撤销更改。
  • 运行语法的菜单项会在有运行进行时等待。没有个案时,分析和排序不可用。
  • 有些菜单项会先显示一个带有语法的询问:删除变量或个案、在拆分开启时排序(排序会结束拆分),以及对超过 100 个变量运行 Frequencies。只有单击按钮才会运行;Escape 取消。

语法窗口

每个语法窗口在带行号的编辑器中容纳一个语法文件或新语法。

  • File > New > Syntax 会打开一个新窗口,在保存之前依次命名为 Syntax1、Syntax2 等。File > Open syntax、Recent files 和拖放的 .sps 文件会在新窗口中打开该文件;如果文件已打开,则将其窗口切换到最前面。
  • Save syntax 和 Save syntax as 保存选择它们时所在的窗口。
  • File > Close 或窗口的关闭按钮会关闭它。如果其文本未保存,会弹出询问,提供 Save、Don’t save 和 Cancel。
  • 工具栏上有 Run all、Run selection 和 Active 列表。Active 列表显示会话中的数据集,并选中活动数据集。选择另一个数据集会运行 DATASET ACTIVATE name.,并像其他运行一样显示在日志中。
  • 所有窗口都在同一个会话和同一个活动数据集上运行。在另一次运行进行时开始的运行会排队等待,状态栏会显示有多少次运行在等待。
  • 对话框或输出中的 Paste 会将语法放到指定语法窗口的末尾:即最后打开的那个,或用 Window > Designate window 选定的那个。如果没有打开的语法窗口,会新开一个。
  • Agent 窗口。 AI 智能体或 statscraft run -s gui 在此窗口中运行的语法,如果成功,会添加到一个名为 Agent 的语法窗口中,每次运行之前有一行带时间的注释。它在第一次这样的运行时打开,关闭后再次运行时会重新打开。您可以像任何语法窗口一样编辑它、从中运行行并保存它;粘贴的语法永远不会进入这里。智能体还可以读取、编辑和运行您的其他语法窗口,您会在编辑器中实时看到每处更改(在那里按 Ctrl+Z 可撤销)。参见 MCP 服务器。

编辑器

  • 不同颜色标示命令名、子命令、关键字、字符串、数字、注释、宏词(!name 和宏语言的词)以及结束命令的句点。
  • 用 DEFINE 定义的宏,无论定义在编辑器文本中还是会话的先前运行中,在调用处都会以宏的颜色显示,包括出现在命令位置时。
  • Run all 运行全部文本。Run selection(Ctrl+Enter)运行所选行上的命令。在没有命令的行上(例如刚输入的命令下面的空行),它运行上方的命令。
  • 错误会显示在其所在的行和列。
  • 长行会在窗口边缘换行。Edit > Settings > Editor > Wrap long lines 可以关闭此功能。

自动补全

在您输入时,会出现一个列表,提供适合光标位置的内容:

  • 命令开头处的命令名(FRE 或 VAL LAB 等缩写可找到完整名称);
  • / 之后的子命令,以及该命令的关键字;
  • 已打开数据中的变量及其标签;
  • 表达式位置上的函数名;
  • 在文本或会话中用 DEFINE 定义的宏,出现在命令位置和命令内部;
  • ! 之后的宏语言词。

Ctrl+Space 可在任意位置打开列表。方向键选择,Enter 或 Tab 插入所选项,Escape 关闭列表。

查找和替换

Ctrl+F(Edit > Find)在编辑器上方打开查找栏,Ctrl+H(Edit > Replace)打开同一个查找栏并带有替换行。单行内选中的文本会成为要查找的文本。

  • 输入文字后,会跳到光标之后的第一个匹配项。所有匹配项都会被标记,当前选中的标记更醒目,查找栏会显示计数(“2 of 7”)。
  • Enter 或 F3 跳到下一个匹配项,Shift+Enter 或 Shift+F3 跳到上一个,到达文本末尾后循环。
  • Match case 区分大小写。Whole word 跳过较长名称内部的匹配,因此 age 不会找到 age2。
  • Replace(或在替换字段中按 Enter)替换当前选中的匹配项并跳到下一个。Replace all 替换所有匹配项并显示替换数量。在编辑器中按 Ctrl+Z 可撤销替换。
  • Escape 或 Close 关闭查找栏,并将光标放回编辑器中。

编辑器中的帮助

  • 列表中的命令,或鼠标指向的命令名,会显示其摘要和语法。
  • F1 会在一个小窗口中打开光标处命令的完整帮助。

Window 菜单

每个窗口都有相同的菜单栏。Window 菜单列出已打开的窗口;单击可将其切换到最前面。指定语法窗口和指定输出窗口标有 +。Designate window 会将选择它时所在的语法窗口或输出窗口设为同类中的指定窗口;对于输出窗口,它运行 OUTPUT ACTIVATE name.。

最后一个窗口关闭时,无论它是哪一类,程序都会退出。

输出窗口

会话中的每个输出文档都有一个输出窗口,以文档命名(Document1、Document2 等,或 OUTPUT NAME 指定的名称)。每次运行的表格都进入指定文档,因此会显示在它的窗口中。

  • 会话中的第一批表格会创建 Document1,并打开其窗口。
  • File > New > Output 运行 OUTPUT NEW.:打开一个新窗口并成为指定窗口。
  • 在输出窗口中,Window > Designate window 运行 OUTPUT ACTIVATE name.。在语法中输入的 OUTPUT NEW、OUTPUT ACTIVATE 和 OUTPUT NAME 也以同样的方式改变窗口。
  • File > Close 或窗口的关闭按钮运行 OUTPUT CLOSE name.。如果窗口中有未保存的输出,会先询问:Save、Don’t save 或 Cancel。指定窗口关闭后,下一批表格会创建新的文档和窗口。

每个输出窗口在导航器旁显示其表格,导航器按运行和命令对表格分组。在导航器中单击某次运行可将其折叠。

输出显示的内容

输出中显示的所有内容都是导航器中的一个元素。每个命令下依次是它的标题(第一张表格上方的那一行,例如“CTABLES, line 36”)及其表格和图表,每张表格和图表都带有其标题,如有注释也带有注释。

  • 导航器中每个元素旁都有一个复选框。取消勾选可隐藏该元素,再次勾选可重新显示。被 OUTPUT MODIFY 隐藏的表格,其复选框一开始就未勾选。
  • Edit > Settings > Grids and output > Show in the output 显示或隐藏整类内容:命令标题(默认关闭)、标题、表格、表格下方的注释以及图表(默认开启)。
  • 当元素所属的类别开启且该元素本身未被隐藏时,它才会显示。不显示的表格或图表会连同其标题和注释一起隐藏,所有表格都被隐藏的命令也不显示命令标题。
  • 不显示的元素在导航器中以灰色斜体显示。输出会立即合拢,填补它留下的空白。
  • 图表的注释是指其副标题和脚注。
  • 隐藏只影响窗口:OUTPUT SAVE 会保存全部内容,并带上 OUTPUT MODIFY 设置的隐藏标记。被 OUTPUT MODIFY /SELECT HEADINGS ... VISIBLE=NO 隐藏的命令标题,仅相当于取消勾选该命令的 Command headings 复选框;其表格仍保留。

表格的外观

  • 每张表格都有多级表头。其说明文字和注释位于表格之后。
  • 列宽与其中的数字相适应,数字右对齐。
  • 较长的行标签和列标题会在单词之间换行。
  • 在同一外层标签下重复的行标签只显示一次,位于其所有行的旁边。

选择表格

  • 运行不会选中任何内容,因此其表格显示时没有边框。
  • 单击表格或导航器中的表格名称即可选中。Ctrl+单击选择更多;Ctrl+A 或 Select all 全选。
  • 再次单击已选中的表格、按 Escape 或在表格旁边单击,可清除选择。
  • 所选表格对应命令的语法会按实际运行时的原样显示在导航器下方,并带有 Copy、Paste(粘贴到指定语法窗口)和 Run again 按钮。将鼠标指向导航器中的命令也会显示其语法。

处理表格

表格上方的按钮作用于所选表格。右键单击表格会提供相同的操作。

  • Copy(Ctrl+C)将表格连同其版式放到剪贴板上,可粘贴到文字处理软件或电子表格中,同时附带纯文本版本。
  • Copy as text 给出制表符分隔的文本。
  • Delete 将它们从窗口及其输出文档中删除,因此 OUTPUT SAVE 和 OUTPUT EXPORT 也不会包含它们。日志会以一行注释显示这次删除。在有运行进行时,Delete 会等待:运行结束时状态栏会提示您再试一次。
  • Export… 打开 Export 对话框(见下文),并设为只导出这些表格。
  • Clear output 以同样的方式删除所有表格。

复制和导出(网页、PDF、Excel,无论通过这些按钮还是通过 File 菜单)只包含输出中显示的内容:不包括隐藏的表格,也不包括未显示的命令标题、标题或注释。标题未显示的表格在 Excel 中没有标题行,但其工作表和 PDF 书签仍保留其名称。在 Export 对话框中开启 Hidden items too 后,它们会包含全部内容;该选项会被记住,复制也会遵循它。

图表

图表在输出中以图片形式显示,宽度与窗口相同,最多约 760 像素,与表格位于同一页面上。

  • 条形图、饼图、折线图、面积图、散点图和直方图都会绘制出来,图表带误差条时也会绘制误差条。
  • 统计图也一样:箱线图、Q-Q 图和 P-P 图、ROC 曲线、树状图、冰柱图、树形图和领域图。
  • 茎叶图和三维图以其数据表的形式显示。

右键单击图表时,除 Copy、Copy as text 和 Delete 外,还提供:

  • Show data:在图表的位置以表格形式显示图表的数字;Show chart 恢复图片。
  • Save chart as PNG… 和 Save chart as SVG…:将图片保存为文件,宽 640 像素(PNG 的像素数为两倍),背景与输出中显示的页面相同。

Office 程序中的图表

条形图、饼图、折线图和面积图会以这些程序自己的真实图表形式进入 PowerPoint、Word 和 Excel。其数字保存在图表内部的一个工作簿中,因此 Edit Data 可以打开它们。这些图表没有自己的颜色,因此会采用演示文稿或文档的主题。统计图(例如直方图或箱线图)以图片形式插入。

右键单击已绘制的图表时,提供:

  • Open in PowerPoint:一个只有一张幻灯片的演示文稿,以图表标题作为幻灯片标题。
  • Open in Excel:一个工作簿,包含图表的数据表,图表位于其旁边。
  • Open in Word:一个包含该图表的文档。

每一项都会将文件写入临时文件夹,并用系统为该文件类型设定的程序打开,因此打开的也可能是其他办公套件。如需保留,请在该程序中保存。

对单个选中的图表使用 Copy,会将其作为可编辑图表放到 Windows 剪贴板上,同时附带制表符分隔的数据文本和 PNG 图片,因此只接受图片的程序会粘贴图片。粘贴到 PowerPoint 或 Word 中时,它会成为这些程序自己的图表,采用幻灯片或文档的主题,Edit Data 可以打开其数字。Excel 粘贴这样的图表时不带数据,与粘贴从 PowerPoint 复制的图表一样;请改用 Open in Excel。在 macOS 和 Linux 上,Copy 会像对待任何表格一样,将图表的数据表放到剪贴板上。

保存输出

窗口的输出可以保存为 Statscraft 输出文件(.scout),以后再次打开,其中包含每条命令的语法、警告、表格和图表。

  • File > Save output 将选择它时所在输出窗口的文档(在其他窗口中则为指定输出窗口的文档)写入它原来的文件或上次保存的文件;第一次保存时会要求指定文件。File > Save output as 总是会询问。两者都运行 OUTPUT SAVE NAME=name OUTFILE='...'.,因此这一步会记录在日志中。
  • File > Open output 运行 OUTPUT OPEN FILE='...'.。文件会作为新文档在单独的窗口中打开,表现为以文件命名的一次运行,并成为指定文档:下一批表格会加入其中,保存时会将新旧内容一起写入。
  • 窗口会记录哪些内容已保存。自打开或保存以来输出有变化的窗口在关闭前会询问,程序在退出前也会询问。
  • .scout 文件是纯 JSON,每行一个表格行,因此任何文本工具或 AI 智能体都能读取它。参见命令行。

导出全部输出

通过这种方式,您可以将表格导出到 Excel、网页或 PDF 文件。

  1. 选择 File > Export…。在数据窗口或语法窗口中,这会导出指定输出窗口。
  2. 选择 Format。对于 Excel 工作簿,选择 One sheet per table 或 All tables on one sheet。
  3. 在 Items 下,选择输出的全部项目或仅所选表格,以及是否包含 Hidden items too。
  4. 单击 Export… 并选择保存位置。对话框会记住您的选择,供下次导出使用。

Excel 工作簿:

  • 每张表格的标题为粗体,列标题在每一级都使用合并单元格,并带有行标签、细边框,说明文字位于下方。每张表格一个工作表时,每个工作表以其表格命名。
  • 数字仍是数字,并带有与输出显示方式一致的格式:百分比单元格保存精确值,并显示为 45.2%。日期、时间和货币值是带有日期、时间或货币格式的数字,因此 Excel 可以用它们计算。
  • 显著性字母和隐藏的小计数(例如 <5)仍为文本。
  • 条形图、饼图、折线图或面积图以其数据表的形式插入,旁边是一张根据这些单元格绘制的可编辑 Excel 图表:修改数字,图表会随之变化。图表采用工作簿的主题。统计图(例如直方图或箱线图)以图片形式插入在其数据表旁边。
  • 插件可以添加颜色、字体、列宽和批注,批注会成为单元格注释。

其他格式:网页包含表格,每张图表以图片形式嵌在页面中。PDF 文件使用 A4 页面,表格为文本,图表为矢量图,并带有命令及其项目的书签。

不使用窗口:statscraft run job.sps --xlsx tables.xlsx 将一次运行的表格写入同样的工作簿(参见 Excel 导出)。窗口打开时,statscraft export 和 MCP 工具 export_output 会以相同的选项导出其输出窗口(参见导出)。在语法中,OUTPUT EXPORT 将输出文档写入工作簿、Word 文档、演示文稿、网页、文本或 CSV 文件。

自定义表格

Analyze > Custom Tables… 按组构建计数、百分比或均值表格,并可标出有显著差异的组。大多数调查报告都由这样的表格组成。该对话框写出一条 CTABLES 命令。

例如,使用示例文件:将 satisfaction 放入 Rows,将 region 放入 Columns,勾选 Column % 和 Compare column proportions,然后单击 OK。表格会显示每个地区有多少客户给出了各个答案,并用字母标出有差异的地区。入门中展示了结果。

构建表格

左侧列表包含活动数据集的变量,Multiple response sets 下是文件中的多重响应集。单击一个或多个名称选中它们,然后单击某个框旁边的 Add。单击框中的名称可将其移出。

  • Rows (categories or sets):这些变量和多重响应集的类别构成行。多个变量上下堆叠。
  • Columns (categories or sets):您要比较的组,并排排列。多个变量左右并排堆叠。
  • Layers (a table for each category):每个类别一张单独的表格,例如每个地区一张表格。
  • Means of (scale variables, in the rows):尺度变量,例如年龄或消费额。其均值显示在单独的一行中。

对话框底部的语法会随您的操作而变化。OK 运行它,Paste 将它放入语法窗口,以便您以后修改它,或在新数据上再次运行。

计数和百分比

在 Summaries 下选择每个单元格显示的内容:

  • Count:个案数,开启权重时为加权个案数。
  • Column %:各列的百分比。每列加起来为 100%,因此您可以比较各列中的组。
  • Row %:各行的百分比。
  • Mean:Means of 下各变量的均值。
  • Totals:一个总计行和一个总计列。
  • Effective count,配合 Effective base weight:对于加权的调查数据,指权重作用后实际有效的样本量。

Hide counts below 隐藏较小的计数,例如为了保护小组中的受访者。低于该数值的计数显示为 <5。

类别和总计

表格中有变量后,即可打开 Categories, totals and subtotals。在 Set the categories of this variable 下选择一个变量,然后:

  • Sort by 按其值、标签、计数或某个尺度变量的均值,升序或降序排序。
  • Total, labeled:仅为此变量添加总计,使用您自己的标签,置于其类别之前或之后。
  • Show user-missing values as categories,例如“Don’t know”。
  • Subtotals:单击 Add subtotal,为其设置标签,并选择它要相加的类别,例如为代码 4 和 5 设置“Top two”。Hide the categories a subtotal sums 只显示小计。Show the categories outside the subtotals 保留其余类别。

Back to the defaults 清除该变量的设置。

显著性检验

检验要求 Columns 中有变量。

  • Chi-square test of independence:每对行变量和列变量做一次检验,结果放在单独的表格中。它说明行是否与列有关。
  • Compare column proportions:对每一行,比较每对列的列百分比。
  • Compare column means:对 Means of 下的每个变量,比较每对列的均值。

Significance level 为 0.05,除非您修改它。列较多时,要检验的列对也多,因此会调整显著性:Bonferroni(默认)、Benjamini-Hochberg 或 No adjustment。

Letters of the column comparisons 选择结果的放置位置:

  • In a table of their own(默认):每列获得一个大写字母(A、B、C 等)。第二张表格重复各行,其中每个单元格显示它显著高于的那些列的字母。
  • In the main table, column keys:每列获得一个键(a、b、c 等),单元格显示它显著高于的那些列的键。
  • In the main table, shared letters (APA):有相同字母的列之间没有差异;没有共同字母的列之间有差异。

表格下方的注释会写明检验方法、显著性水平和调整方法。

多重响应集

多重响应集是允许多选的一道问题,存储为多个变量。在示例文件中,五个是/否变量记录客户使用了哪些渠道,多重响应集 $channels 将它们组合在一起。

  • Define a set with Data > Define Multiple Response Sets…. A dichotomy set counts one value (such as 1 for “used”) across its variables. A category set gathers the codes of several variables (first answer, second answer and so on). Saving the data keeps the set in the file. The dialog lists the sets already in the dataset under Defined sets with their type, label and variables. Click a set or Edit to load it into the form, change it and save it under the same name.
  • 像变量一样将多重响应集放入 Rows 或 Columns。每个答案成为一行或一列。
  • 多重响应集的百分比以受访者为基数,因此一列加起来可能超过 100%。没有给出任何答案的受访者不计入该集。
  • 检验也适用于多重响应集。表格下方的注释会说明检验如何考虑一名受访者可以属于多个类别这一情况。

Excel 中的自定义表格

使用 File > Export… 和 Excel workbook 导出输出。每张表格都保留其表头层级、标签和说明文字,数字仍为数字,显著性字母仍为文本。要将多张表格放在一个工作表上,请选择 All tables on one sheet。导出全部输出介绍了该工作簿。

插件可以在窗口和工作簿中为自定义表格的单元格着色和添加批注。

每个窗口的菜单栏都相同:File、Edit、Data、Analyze、Graphs、Transform、Window 和 Help。Data、Analyze、Graphs 和 Transform 中的菜单项会打开一个写出命令的对话框。每条命令都有单独的页面,列出所有选项,链接见下表。

文件

  • Open data…、Save data、Save data as… 和 Export data…(参见打开文件和导出数据)。Save data 保存选择它时所在数据窗口的数据集,在其他窗口中则保存活动数据集。
  • Apply Data Dictionary… 从另一个数据文件复制标签、格式和缺失值(APPLY DICTIONARY)。
  • New > Data、New > Syntax 和 New > Output、Open syntax…、Open output… 以及 Recent files。
  • Save syntax、Save syntax as…、Save output、Save output as… 和 Export…(参见保存输出和导出全部输出)。
  • Output Management > Start… 和 End… 在语法运行时将表格发送到文件(OMS、OMSEND)。
  • Close 和 Exit。

Edit

  • Undo(Ctrl+Z)和 Redo(Ctrl+Y 或 Ctrl+Shift+Z):参见语法是唯一的命令层。每个菜单项都会写明它将撤销或重做的运行。
  • Settings…:参见设置。

Data

菜单路径功能 {#what-it-does}命令
Define Multiple Response Sets将变量组合为多重响应集MRSETS
Sort Cases按一个或多个变量对个案排序SORT CASES
Sort Variables按名称、标签、类型等属性对变量排序SORT VARIABLES
Restructure变量转为个案、个案转为变量,或交换个案和变量VARSTOCASES, CASESTOVARS, FLIP
Split File按组运行每项分析SPLIT FILE
Select Cases将个案排除在分析之外,或删除它们FILTER, SELECT IF
Select Cases by Time Range时间序列分析所用的个案USE
Weight Cases按某个变量对个案加权WEIGHT
Aggregate按组计算统计量,添加到个案中或作为新数据集AGGREGATE
Define Dates时间序列的日期变量DATE
Orthogonal Design > Generate, Display联合分析研究的设计及其卡片ORTHOPLAN, PLANCARDS
Validation > Validate Data, Compare Datasets按规则检查值,或比较两个数据集VALIDATEDATA, COMPARE DATASETS
Merge Files > Add Cases, Add Variables追加另一个文件的个案,或按键变量合并其变量ADD FILES, MATCH FILES

Analyze

每个菜单项都会打开一个写出一条命令的对话框。命令页面列出对话框提供的所有选项,以及更多选项。

菜单路径功能 {#what-it-does}命令
Reports > Codebook每个变量的说明,包括其标签和统计量CODEBOOK
Reports > Case Summaries各组的统计量,以及个案列表SUMMARIZE
Reports > OLAP Cubes各组的总计和均值,以及组间差异OLAP CUBES
Power Analysis > Means, Proportions, Correlations, Regression检验的功效或所需的样本量;不需要数据POWER MEANS ONESAMPLE 及其他 POWER 命令
Simulation > Build Simulation Plan, Run Simulation根据您选择的分布对模型进行模拟SIMPLAN, SIMRUN
Descriptive Statistics > Frequencies每个值的计数表,带有统计量FREQUENCIES
Descriptive Statistics > Descriptives尺度变量的均值、标准差和全距DESCRIPTIVES
Descriptive Statistics > Explore按组给出描述统计量、百分位数和正态性检验EXAMINE
Descriptive Statistics > Crosstabs两个或多个变量的表格,带有检验CROSSTABS
Descriptive Statistics > Ratio两个变量之比的统计量RATIO STATISTICS
Bayesian Statistics > One Sample, Related, Independent均值、比例或比率的贝叶斯检验BAYES ONESAMPLE, BAYES RELATED, BAYES INDEPENDENT
Bayesian Statistics > Pearson Correlation, One-way ANOVA, Linear Regression, Repeated Measures, Log-Linear Regression Models贝叶斯相关、方差分析、回归和表格BAYES CORRELATION, BAYES ANOVA, BAYES REGRESSION, BAYES REPEATED, BAYES LOGLINEAR
Custom Tables计数、百分比和均值的表格,带有显著性检验;参见自定义表格CTABLES
Compare Means > Means各组的均值和其他统计量MEANS
Compare Means > One-Sample, Independent-Samples and Paired-Samples T Test均值的 t 检验T-TEST
Compare Means > One-Way ANOVA单因素方差分析,带事后检验ONEWAY
Compare Means > Proportions比例及其差异的检验和区间PROPORTIONS
General Linear Model > Univariate单个因变量的方差分析和协方差分析UNIANOVA
General Linear Model > Multivariate, Repeated Measures多个因变量,或单个因变量的重复测量GLM
General Linear Model > Variance Components每个随机因子对方差的贡献大小VARCOMP
General Linear Model > MANOVA (classic)多元方差分析MANOVA
Generalized Linear Models计数、比例和其他非正态响应的模型GENLIN
Mixed Models > Linear带随机效应和重复测量的线性模型MIXED
Mixed Models > Generalized Linear带随机效应的广义线性模型GENLINMIXED
Correlate > BivariatePearson、Spearman 和 Kendall 相关CORRELATIONS, NONPAR CORR
Correlate > Partial控制其他变量后的相关PARTIAL CORR
Correlate > Distances个案或变量之间的距离或相似性PROXIMITIES
Regression > Linear线性回归,带逐步选择和诊断REGRESSION
Regression > Curve Estimation二次、对数和指数等曲线CURVEFIT
Regression > Quantile中位数或其他分位数的回归QUANTILE REGRESSION
Regression > Binary Logistic是/否结果的 logistic 回归LOGISTIC REGRESSION
Regression > Optimal Scaling (CATREG)分类变量的回归CATREG
Regression > 2-Stage Least Squares带工具变量的回归2SLS
Regression > Multinomial Logistic多类别结果的 logistic 回归NOMREG
Regression > Ordinal有序结果的回归PLUM
Regression > Probit响应率的 probit 和 logit 模型PROBIT
Regression > Weight Estimation加权最小二乘法WLS
Regression > Partial Least Squares基于众多预测变量的成分进行回归PLS
Loglinear > General, Logit表格的对数线性模型和 logit 模型GENLOG
Loglinear > Model Selection分层对数线性模型HILOGLINEAR
Classify > K-Means Cluster将个案分为指定数量的聚类QUICK CLUSTER
Classify > Hierarchical Cluster个案或变量的聚类,带树状图CLUSTER
Classify > TwoStep Cluster大型文件的聚类,可用分类变量和尺度变量TWOSTEP CLUSTER
Classify > Attribute Importance (AIM)哪些变量区分了聚类或组AIM
Classify > Feature Selection (SELECTPRED)与目标变量关系最密切的预测变量SELECTPRED
Classify > Identify Unusual Cases与同类个案不同的个案DETECTANOMALY
Classify > Discriminant判别分析,带分类DISCRIMINANT
Classify > Tree分类树和回归树TREE
Classify > ROC AnalysisROC 曲线,带检验之间的比较ROC ANALYSIS
Classify > Response Rate按得分组计算的增益和响应率RESPONSE RATE
Classify > Nearest Neighbork 最近邻分类KNN
Classify > Naive Bayes朴素贝叶斯分类NAIVEBAYES
Neural Networks > Multilayer Perceptron, Radial Basis Function神经网络模型MLP, RBF
Dimension Reduction > Factor因子分析和主成分分析FACTOR
Dimension Reduction > Correspondence Analysis表格的对应分析CORRESPONDENCE
Dimension Reduction > Multiple Correspondence多个分类变量的对应分析MULTIPLE CORRESPONDENCE
Dimension Reduction > Categorical Principal Components基于最优尺度的主成分分析CATPCA
Dimension Reduction > Older Optimal Scaling Commands同质性分析、非线性主成分分析和典型相关分析,以及旧版对应分析HOMALS, PRINCALS, OVERALS, ANACOR
Scale > Reliability AnalysisCronbach’s alpha 和其他信度模型RELIABILITY
Scale > Multidimensional Scaling (PROXSCAL), (ALSCAL)根据对象间距离绘制的对象图PROXSCAL, ALSCAL
Scale > Multidimensional Unfolding (PREFSCAL)偏好图PREFSCAL
Scale > Weighted Kappa, Fleiss Multirater Kappa评分者之间的一致性WEIGHTED KAPPA, FLEISS MULTIRATER KAPPA
Scale > Conjoint偏好评分的联合分析CONJOINT
Nonparametric Tests > One Sample, Independent Samples, Related Samples根据数据选择的非参数检验NPTESTS
Nonparametric Tests > Legacy Dialogs卡方检验、二项检验、游程检验、Mann-Whitney 检验、Wilcoxon 检验及其他检验NPAR TESTS
Survival > Life Tables寿命表SURVIVAL
Survival > Kaplan-MeierKaplan-Meier 生存曲线KM
Survival > Cox RegressionCox 比例风险回归COXREG
Forecasting > Exponential Smoothing, ARIMA, Autoregression时间序列模型EXSMOOTH, ARIMA, AREG
Forecasting > Create Models, Apply Models为每个序列寻找最佳模型,并应用已保存的模型TSMODEL, TSAPPLY
Forecasting > Autocorrelations, Cross-Correlations序列的自相关,以及序列之间的相关ACF, PACF, CCF
Forecasting > Seasonal Decomposition, Spectral Analysis季节因子和周期成分SEASON, SPECTRA
Forecasting > Sequence Charts随时间绘制的序列TSPLOT
Forecasting > Forecast Period, Options要预测的个案,以及时间序列命令的设置PREDICT, TSET
Quality Control > Control Charts过程的控制图SPCHART
Multiple Response > Frequencies, Crosstabs多重响应集的表格MULT RESPONSE
Missing Value Analysis缺失值的模式,带估计值MVA
Multiple Imputation > Analyze Patterns, Impute Missing Data Values缺失值的模式,以及数据的插补副本MULTIPLE IMPUTATION
Complex Samples > Sampling Plan, Select a Sample设计样本并抽取样本CSPLAN, CSSELECT
Complex Samples > Analysis Plan描述样本是如何抽取的CSPLAN
Complex Samples > Descriptives, Frequencies, Crosstabs考虑抽样设计的估计值和表格CSDESCRIPTIVES, CSTABULATE
Complex Samples > General Linear Model, Logistic Regression, Ordinal Regression, Cox Regression考虑抽样设计的模型CSGLM, CSLOGISTIC, CSORDINAL, CSCOXREG

Graphs

菜单路径功能 {#what-it-does}命令
Chart Builder条形图、折线图、面积图和饼图、直方图、散点图、误差条图、Pareto 图和高低图GRAPH
P-P Plots, Q-Q Plots将变量与检验分布进行比较PPLOT
ROC Curve检验变量的 ROC 曲线ROC
Case Plots逐个个案绘制的序列,个案沿页面向下排列CASEPLOT

Transform

菜单路径功能 {#what-it-does}命令
Compute Variable根据表达式生成的新变量,适用于所有个案或仅满足条件的个案COMPUTE, IF
Recode用新代码替换旧代码,放在同一变量或新变量中RECODE
Count Values within Cases给定值在各变量中出现的次数COUNT
Rank Cases秩、百分位数组和正态得分RANK
Optimal Binning根据与目标变量的关系对尺度变量分组OPTIMAL BINNING
Prepare Data for Modeling (ADP)为建模清理和转换变量ADP
Automatic Recode为变量的值分配连续代码,并以旧值作为标签AUTORECODE
Create Time Series从现有序列生成新序列:差分、滞后、移动平均等CREATE

Window

参见 Window 菜单。

Help

  • Documentation 在线打开本文档。
  • About Statscraft 显示版本、许可证(MIT)、源代码和文档的链接,以及颜色主题和字体的许可证。
  • Check for updates:参见更新。

对话框

每个构建语法的对话框都以相同的方式结束。这适用于菜单中的对话框,也适用于 Variables 标签页中类型和格式、值标签和缺失值的编辑器。

  • 显示它构建的语法,或说明为何尚无语法。
  • OK 运行语法,Paste 将其放入指定语法窗口,Cancel 关闭对话框。菜单中的对话框还有 Reset。
  • 语法完整之前,OK 和 Paste 不可用。Escape 取消。
  • 保持默认值的选项不会向语法中添加任何内容。

状态栏和日志

状态栏:

  • 显示正在运行的内容,以及其后有多少次运行在等待;
  • 显示一次运行产生了多少条警告(警告显示在日志中对应命令的下方);单击此处会显示日志,在数据窗口中单击则会将指定输出窗口切换到最前面;
  • 无论在哪个标签页,都会显示错误;
  • 在右侧列出生效的拆分、过滤和权重,例如 Split by region (layered)、Filter: filter_$ 和 Weight: weight。单击其中之一会打开 Split File、Select Cases 或 Weight Cases。

日志位于每个语法窗口和输出窗口中:

  • 列出每条命令及其所做的更改;
  • 带有 Copy syntax,它给出一个用 statscraft run 重现该会话的脚本;
  • 可通过 Edit > Settings > Grids and output > Log under Syntax and Output 关闭。有警告的运行即使在日志关闭时也会显示日志。

数据窗口没有日志,因此网格占据整个高度。

语法是唯一的命令层

窗口中的每项更改和每个结果都来自引擎运行的语法,与 statscraft run 的运行方式完全相同。

  • 打开文件会运行 GET FILE 和带下一个可用名称(DataSet1、DataSet2 等)的 DATASET NAME,因此之前打开的数据仍在会话中保持打开。
  • 编辑单元格会运行 IF ($CASENUM = n) var = value.
  • 编辑标签会运行 VARIABLE LABELS,依此类推。
  • 一次运行中定义的宏(DEFINE,或 INCLUDE 宏库)在窗口打开期间对之后的运行保持定义,SET 的宏设置也一样。
  • Edit > Undo(在文本字段之外按 Ctrl+Z)会恢复上一次更改数据集的运行之前的数据集,以及当时打开的数据文件。每用一次就再往前退一次运行,最多 10 次;对于非常大的文件,如果保存的状态会占用超过 1 GB 不与当前数据共享的内存,窗口会保留较少的状态,但总会保留最新的一个。日志会将每次被撤销的运行标记为 undone,Copy syntax 不会包含它。
  • Edit > Redo(在文本字段之外按 Ctrl+Y 或 Ctrl+Shift+Z)会重新执行上一次撤销的运行,每用一次重做一次运行,日志也不再将其标记为 undone。撤销后再运行一次更改数据的命令会结束重做。在这两个方向上,输出都保持不变。命令行和智能体可以用 statscraft undo、statscraft redo 以及 MCP 工具 undo 和 redo 做同样的事。
  • 运行进行时,窗口仍保持响应。状态栏会显示正在运行的内容。
  • 一次只进行一次运行。来自所有窗口的运行和来自命令行的请求按到达顺序排队等待。

设置

Edit > Settings 在一个对话框中包含窗口的全部设置,各部分列在左侧的列表中。更改会立即生效并保存。Close 或 Escape 关闭对话框。

  • Language(语言)

    • Language of the window(窗口语言):System(默认)、English、Español、Português (Brasil)、Deutsch 或 Français。请参阅窗口的语言。
  • Editor

    • Syntax colors:语法编辑器的颜色和背景。Statscraft Light(默认)和 Statscraft Dark 采用 Statscraft 的配色。现成的编辑器主题有 Catppuccin Latte 和 Mocha、One Dark、Solarized Light 和 Dark,以及 GitHub Light 和 Dark。
    • Wrap long lines(默认开启)会在窗口边缘换行。
  • Grids and output

    • Paper of the grids and the output:指 Data 和 Variables 网格以及输出表格。Always light(默认)让它们始终是浅色底上的深色文字,就像电子表格或文档页面一样,而菜单、面板和对话框则跟随系统的深色或浅色主题。Follow the system theme 让它们也采用系统主题。
    • Log under Syntax and Output(默认开启)。
    • Show in the output:Command headings(默认关闭)、Titles、Tables、Notes under tables 和 Charts(默认开启)。参见输出显示的内容。
    • Variables in tables(Labels、Names 或 Names and labels)和 Values in tables(Labels、Values 或 Values and labels)。这些设置属于会话,而不是窗口。选择后会像其他命令一样运行 SET TVARS 或 SET TNUMBERS,显示在日志中,并对之后的运行保持有效。语法中的 SET 也会改变对话框中的设置。窗口会记住您的选择,并在启动时重新设置,因此您只需设置一次。
    • Output for multiply imputed data:Original data、Each imputation、Pooled 和 Diagnostics,适用于在按 Imputation_ 拆分的数据上运行的过程。更改时会运行 SET MIOUTPUT=[...];至少有一项保持勾选。与表格标签设置一样,它属于会话,窗口启动时会重新设置它。
  • Updates

    • Check for updates automatically:参见更新。
  • AI agents

    • 一键将 Statscraft MCP 服务器添加到本机的各个 AI 应用中,或再次移除,每个应用单击一次,并告诉您需要重启什么。对于 Claude Desktop,Install extension 会下载并打开此版本的 Statscraft 扩展。Check 显示每个应用的设置文件,以及其中当前是否有该条目。参见连接您的 AI 智能体。
  • Plugins

    • 已安装的插件,即为自定义表格的单元格着色和添加批注的程序,按运行顺序排列。参见插件。

窗口的语言

窗口支持英语、西班牙语、巴西葡萄牙语、德语和法语。在 Edit > Settings > Language 中选择:

  • System(默认)跟随计算机的语言:系统设置为西班牙语、巴西葡萄牙语、德语或法语时使用该语言,否则使用英语。
  • English、Español、Português (Brasil)、Deutsch 或 Français:无论系统如何设置,都保持该语言。

菜单、工具栏、状态栏、Settings 对话框、网格的标题和右键菜单,以及对话框中的 OK、Paste、Reset 和 Cancel 按钮,会在您选择后立即切换,无需重新启动。

有几样内容在所有语言中都保持不变:

  • 语法:其命令和关键字,以及对话框编写和粘贴的语法。
  • 输出表格的内容和命令的消息。
  • 命令行和 MCP 服务器,AI 智能体读取的就是它们。
  • 变量、文件、数据集和命令的名称,以及 Statscraft 这个名称。

窗口记住的内容

在不同会话之间,窗口会记住每类窗口的大小和位置、上次文件对话框的文件夹、最近的十个文件(File > Recent files)、Variables 标签页的列宽,以及 Edit > Settings 中的每项选择。新窗口会在同类窗口上次所在的位置打开,并相对已打开的窗口稍向右下方偏移。

关闭与未保存的工作

最后一个窗口关闭时程序退出,也可以通过 File > Exit、Windows 更新安装程序或 Restart now 退出。退出前会先检查每个窗口中是否有未保存的工作。

  • 未保存的工作包括:自上次打开或保存以来有更改的数据集、文本与其文件不同的语法、非空的新语法,以及自打开或保存以来添加或删除了表格的输出文档。
  • 以 GET、GET DATA 或 SAVE 结束的运行之后,数据视为已保存,无论运行来自菜单、语法窗口还是命令行。
  • 如果没有未保存的内容,程序会立即退出。
  • 否则会弹出一个询问,列出未保存的内容,提供 Save、Don’t save 和 Cancel。
    • Save 会保存每个窗口的语法、每个有更改的输出文档和每个有更改的数据集,各自保存到其文件,尚无文件时则通过文件对话框保存。全部写入后程序退出。取消文件对话框或保存失败时,程序保持打开。
    • Cancel、Escape 或在询问框旁边单击,程序保持打开。

在其他窗口仍打开时关闭一个窗口,只会询问该窗口自己的工作:语法窗口的语法、数据窗口的数据、输出窗口的输出。

更新

有新版本发布时,菜单下方会出现一个提示栏,带有发布说明的链接、Update now 和 Later。Help > Check for updates 会立即检查。安装和更新介绍了 Update now 对每种安装方式的作用,以及如何关闭每日检查。

与 AI 智能体协作

窗口打开时,命令行和 AI 智能体可以在其中工作:它们的语法在这里运行,您会看到每张表格和每条命令出现。参见实时窗口会话,以及 Statscraft 与 AI 智能体中关于智能体应如何使用它的说明。

字体

窗口自带字体,两者都采用 SIL Open Font License:

  • Schibsted Grotesk 用于菜单、对话框、网格和输出,其数字等宽,因此数字在列中对齐;
  • JetBrains Mono 用于语法。

它们缺少的字符(例如 Schibsted Grotesk 中的西里尔字母)来自系统字体:Windows 上为 Segoe UI 和 Consolas,macOS 上为 Arial 和 Courier New,Linux 上为 DejaVu、Noto 或 Liberation。将 STATSCRAFT_FONT 或 STATSCRAFT_MONO_FONT 设为一个 .ttf 文件,即可优先使用另一种字体。

Statscraft 0.61.0, release v0.61.0

命令行

statscraft describe   dictionary and counts of a data file or a session
statscraft run        run syntax
statscraft check      validate syntax without saving or writing anything
statscraft chart      add a chart given as JSON to the output
statscraft export     export the output of the open window, as its File > Export
statscraft output     show what an output window of the open window holds
statscraft undo       take back the last change to the data in the open window, as its Edit > Undo
statscraft redo       do again what the last undo took back, as its Edit > Redo
statscraft help       syntax of a command, or the list of commands
statscraft plan       lower syntax to an OpenStatSpec transformation plan
statscraft db         store datasets in an OpenStatSpec database and read them back
statscraft update     check for a newer release, or update this installation to it
statscraft mcp        serve these tools to an AI agent over MCP
statscraft connect    add the Statscraft MCP server to the AI agents on this computer

statscraft --version 打印版本号,statscraft <subcommand> --help 列出某个子命令的选项。示例使用示例文件 survey.sav 或您自己的数据文件,job.sps 代表您自己的语法文件。plan 和 db 有单独的页面:数据库。

describe

statscraft describe FILE [--json]
statscraft describe -s SESSION [--json]
选项含义
FILE.sav 或 .zsav 文件
-s, --session NAME改为描述一个会话:它的数据集和它保存的状态;gui 表示打开的窗口
--json以 JSON 输出完整的字典,而不是每个变量一行;如果数据文件有属性,则放在 attributes 下(每个名称及其值列表)

请给出文件或会话之一。文本形式先打印 cases, variables,然后每个变量一行,列出名称、格式、测量级别、有效计数和标签,以制表符分隔。对于会话,接着列出会话在数据之外保存的内容,有内容时每项一行:settings:、PRESERVE levels:、directory:(相对文件名的起点:最后一次 CD 的文件夹,否则对窗口而言是其最近一个调用方的文件夹)、active dataset:、datasets:、macros:、output documents:、designated output:。在 JSON 中,这些内容位于对象 session 中(参见会话)。

session 中的数据集和输出文档:

字段内容
active_dataset活动数据集的名称,即所有命令所作用的数据集;没有名称时不出现
datasets每个命名数据集,活动数据集在前:name,以及有数据时的 cases 和 variables(仅用 DATASET DECLARE 声明的名称没有这两项)
output_documents每个打开的输出文档,按打开顺序排列:name 和表格数 tables
designated_output下一批表格将进入的文档(由 OUTPUT NEW 和 OUTPUT ACTIVATE 设定);没有打开的文档时不出现,此时下一个表格会新建 Document1
"session": {
  "active_dataset": "DataSet2",
  "datasets": [
    {"name": "DataSet2", "cases": 200, "variables": 19},
    {"name": "DataSet1", "cases": 150, "variables": 12}
  ],
  "output_documents": [{"name": "Document1", "tables": 4}],
  "designated_output": "Document1"
}

打开的窗口(-s gui)以同样的方式列出窗口中的内容。文件会话同样会在多次运行之间保留其输出文档,因此列表显示的是之前各次运行收集的内容。

run

statscraft run [FILE | - | -e TEXT] [-s SESSION] [--lines FIRST-LAST] [--json] [--vega-lite] [--encoding NAME] [--xlsx FILE [--xlsx-one-sheet] [--xlsx-no-titles] [--plugin PROGRAM]... [--plugin-template FILE]...] [--charts DIR [--chart-format svg|png]]
选项含义
FILE语法文件;- 表示从标准输入读取语法
-e, --execute TEXT在命令行上直接给出的语法,代替文件
-s, --session NAME运行前从该会话加载数据集,运行后保存;gui 表示打开的窗口
--lines FIRST-LAST只运行这些行内的命令(从 1 开始计数,包含两端),例如 40-55
--json以 JSON 而不是 Markdown 打印结果
--vega-lite同时将每个图表输出为 Vega-Lite 规范(参见图表)
--encoding NAME语法文件或标准输入的编码,例如 windows-1257 或 1252;不加此选项时,有效的 UTF-8 文件(带或不带字节顺序标记)按 UTF-8 读取,其他文件按系统的旧代码页读取
--xlsx FILE同时将本次运行的每个表格和图表写入 Excel 工作簿,每个表格一个工作表
--xlsx-one-sheet与 --xlsx 一起使用时,将所有表格放在同一个工作表上,上下排列
--xlsx-no-titles与 --xlsx 一起使用时,省略每个表格和图表上方的标题行;变量标签、说明文字和插件添加的内容保留
--plugin PROGRAM与 --xlsx 一起使用时,让插件为自定义表格着色、添加批注和排版(参见插件);其设置来自活动数据的属性,使用 -s gui 时来自窗口活动数据的属性。多个插件可多次给出此选项:它们按给出顺序运行,结果合并,两个插件设置同一样式时以后者为准
--plugin-template FILE与 --plugin 一起使用时,在本次运行中将一个设计模板文件叠加在数据属性之上,效果与窗口中启用的模板相同。模板文件由窗口 Plugin Settings 中的 Export 生成(插件)。每个插件一个文件,每个文件只包含某个 --plugin 程序的一个模板
--charts DIR同时将本次运行的每个图表作为图片写入该文件夹(参见图表图片)
--chart-format svg|png与 --charts 一起使用时的图片格式;默认为 svg

不加 --json 时,每个表格以 Markdown 表格打印在 ### 标题下,每个图表打印为一个数值表,其说明文字指明图表类型,警告打印为 warning: line N: COMMAND: message(命令名只出现一次:本身已提及命令名的消息保留该名称,带子命令时也是如此,如 FACTOR /SAVE:,拆分组的名称跟在其后),最后是摘要:加载的数据集,新增、更改和删除的变量,个案数发生变化时的个案数,以及 ran N command(s),会话已写入时再加上 , session saved。

statscraft run job.sps
statscraft run -s demo -e "FREQUENCIES VARIABLES=gender."
echo "DESCRIPTIVES VARIABLES=age monthly_spend." | statscraft run -s demo -

一次运行要么全部成功,要么全部不生效。任何命令失败时都不保存任何内容:会话不保存,工作簿也不保存。失败命令之前由 SAVE 写入的文件仍留在磁盘上。

check

statscraft check [FILE | - | -e TEXT] [-s SESSION] [--lines FIRST-LAST] [--json] [--vega-lite] [--encoding NAME]

选项与 run 相同,但没有 --xlsx。check 在会话数据集的副本上运行命令,并跳过所有文件写入,因此既能发现语法错误,也能发现依赖数据的错误(未知变量,需要数值的地方给了字符串)。会话和磁盘保持不变。摘要显示 checked N command(s),JSON 中的 saved 始终为 false。

statscraft check -s demo -e "COMPUTE age10 = age / 10."
variables added: age10
checked 1 command(s)

源代码中的所有语法错误一次性报告,每个有错的命令一条。运行时发现的错误在第一个失败的命令处停止。

help

statscraft help                     the supported commands with one line each, then the general rules
statscraft help FREQUENCIES         syntax, notes and an example of one command
statscraft help freq                names may be lowercase and shortened, as in syntax

未知的名称会报错。相同的文本按每个命令一页收录在命令中。

会话和行范围

会话在多次运行之间保留您的工作,就像窗口打开期间那样。用 -s 给它一个名称,每次运行都在上一次的基础上继续:

statscraft run -s demo -e "GET FILE='survey.sav'."
statscraft run -s demo -e "RECODE age (LOWEST THRU 39 = 1) (40 THRU HIGHEST = 2) INTO young_old."
statscraft run -s demo -e "FREQUENCIES VARIABLES=young_old."

会话保存:

  • 活动数据集及其权重、拆分和过滤,以及每个命名数据集;
  • 宏(DEFINE,或用 INCLUDE 引入的宏库)以及 SET 的宏设置;
  • 文件句柄、SET 的值、PRESERVE 层级和最后一次 CD 的文件夹;
  • 随机数的当前位置,因此下一次运行从上一次停止的地方继续;
  • 输出文档及其表格;
  • 每次成功运行的语法,保存在文件 syntax.sps 中:记录会话如何走到当前状态。在原始数据上从头运行它即可重复这些工作。

TEMPORARY、N OF CASES、临时变量和 VECTOR 在给出它们的那次运行结束时失效。未闭合的 DO IF 或 LOOP 会使运行失败。

  • 新会话的第一次运行没有数据,因此通常以 GET FILE 开始。
  • 一次运行要么全部成功,要么全部不生效:一个命令失败时,会话保持原样。修正该行后再运行一次。
  • describe -s NAME 显示活动数据集以及会话保存的内容(参见 describe)。
  • 会话保存在当前文件夹下的 .statscraft/sessions/<name>/ 中。删除该文件夹即可重新开始。
  • 表格在会话的输出中逐次运行累积。OUTPUT CLOSE ALL. 会清空输出。--xlsx 只写入本次运行的表格;要一次写入多次运行的表格,请以 OUTPUT EXPORT 结束(参见 Excel 导出)。

--lines 运行文件的一部分,因此您可以逐段处理一个长脚本:

statscraft run -s demo --lines 1-1 job.sps
statscraft run -s demo --lines 4-6 job.sps

范围必须覆盖完整的命令。范围内的空行和注释没有问题,范围外的语法错误也不会使其停止。截断某个命令的范围会失败:

error: line 1, column 1: line range 2-3 cuts through command FREQUENCIES, which occupies lines 1-2; hint: use lines 1-3 to include the whole command

输出中的行号始终指整个文件中的行,而不是范围内的行。

退出代码

代码情形
0成功,包括带有警告的运行
1语法、运行、文件或会话失败;plan 和 db 打印 "ok":false 时也是如此
2命令行本身有误:未知选项、缺少值、选项相互冲突
10update --check:已发布更新的版本

update

statscraft update --check          current and latest version; exit code 10 when an update exists
statscraft update --check --json   the same as JSON
statscraft update --check --plugin PROGRAM [--json]
                                   whether a plugin offers a newer version; installs nothing
statscraft update                  update this installation to the latest release

最新版本是 GitHub 仓库上最新发布的版本;草稿和预发布版本不算在内。update --check 打印当前运行的版本和最新版本,本副本已是最新时(尚未发布任何版本时也是如此)以 0 退出,有更新的版本时以 10 退出,因此脚本可以使用 statscraft update --check || ...。加上 --json 时,它打印一行:

{"current":"0.1.0","latest":"0.2.0","update":true,"notes":"https://github.com/statscrafthq/statscraft/releases/tag/v0.2.0"}

尚未发布任何版本时 latest 为 null;有更新时 notes 为该版本的发布页面。

update --check --plugin PROGRAM 改为查询一个插件,与窗口中 Edit > Settings > Plugins 里的 Check 相同:它打印插件的名称、版本,插件提供更新版本时还打印该版本及其说明;有更新时退出代码为 10,否则为 0。加上 --json 时:{"plugin":"Acme Tables","current":"0.2.1","latest":"0.2.2","update":true,"notes":"Faster tables"}。它从不安装插件:--plugin 只能与 --check 一起使用,安装插件请使用窗口插件设置中的 Update。不提供更新或无法检查的插件会报错并说明原因。

update 的作用与窗口中的 Update now 相同,具体取决于本副本的安装方式:参见更新。在 Debian 和 Ubuntu 上,它只下载软件包,并打印安装它的命令。从源代码构建的副本,或来自 macOS 软件包的命令行,不会被更新:该命令会说明如何更新,退出代码为 1。

每个下载在运行或替换任何内容之前,都会与随版本发布的校验和进行核对;不匹配时不做任何更改。检查不会发送任何关于您或您的数据的信息。错误的打印方式与其他子命令相同,退出代码为 1。

connect

statscraft connect 为本机安装的每个 AI 智能体添加一个启动 statscraft mcp 的条目,并告诉您需要重启什么。statscraft connect AGENT 只连接一个智能体,--list 只显示状态,--remove [AGENT] 再次删除该条目,--json 以 JSON 打印结果。连接您的 AI 智能体列出了支持的智能体、它所修改的文件以及如何手动进行同样的修改。

Excel 导出

statscraft run job.sps --xlsx tables.xlsx
statscraft run job.sps --xlsx all.xlsx --xlsx-one-sheet
statscraft run -s gui -e "FREQUENCIES VARIABLES=region." --xlsx region.xlsx

本次运行的每个表格和图表都写入工作簿,每个表格一个工作表,以其标题命名。--xlsx-one-sheet 将它们全部放在一个名为 Tables 的工作表上,上下排列。--xlsx-no-titles 省略每个表格和图表上方的标题行,例如用于在一个工作表上堆叠自定义表格。工作簿的样式与窗口导出的相同:参见导出全部输出。终端上的文本输出与不加 --xlsx 时相同。

无法写入的工作簿会使运行失败,此时会话不会保存。

要将多次运行的表格收集到一个工作簿中,请在最后一次运行末尾使用 OUTPUT EXPORT,它会写入会话的整个输出文档:OUTPUT EXPORT /XLSX DOCUMENTFILE='all.xlsx'. OUTPUT EXPORT 还能写入 Word 文档(/DOC)、演示文稿(/PPT)、网页(/HTML)以及图表的图片文件(参见图表图片)。

输出文件

OUTPUT SAVE 将输出文档写为 Statscraft 输出文件(.scout),OUTPUT OPEN 将其读回为一个新文档。窗口保存和打开的是同样的文件(窗口)。

statscraft run -e "GET FILE='survey.sav'.
CROSSTABS region BY gender.
OUTPUT SAVE OUTFILE='region.scout'."
statscraft run -e "OUTPUT OPEN FILE='region.scout'.
OUTPUT EXPORT /XLSX DOCUMENTFILE='region.xlsx' /HTML DOCUMENTFILE='region.html'."

第二次运行在没有数据的情况下转换已保存的输出:OUTPUT OPEN 将文件中的文档设为指定文档,OUTPUT EXPORT 将其写出。OUTPUT OPEN 之后的命令所产生的表格会加入该文档,因此打开、运行、再次保存就会向文件中追加内容。

文件可能来自任何人,因此 OUTPUT OPEN 在显示每个表格和图表之前都会对其进行检查。未通过检查的项会被省略,并给出说明原因的警告,文件的其余部分照常打开。

该文件是纯 JSON,每个表格行占一行,因此智能体或脚本无需调用 Statscraft 即可直接读取。每个命令是一项,包含与运行时完全相同的语法、其警告,以及采用运行结果形式的表格和图表。开发者说明描述了其结构。

图表图片

statscraft run job.sps --charts charts
statscraft run job.sps --charts charts --chart-format png

本次运行的每个图表都写入该文件夹(文件夹不存在时会自动创建),文件名为 01-<title>.svg、02-<title>.svg 等:按输出顺序编号,标题转为小写,单词之间用连字符连接。同名的现有文件会被替换。图片宽 640 像素,白色背景(PNG 的像素数是其两倍,以使文字清晰),绘制方式与窗口相同:扁平的条形、线条、面积、圆点和扇区,采用石油蓝和琥珀色,标签颜色柔和,规则线细,字体为 Schibsted Grotesk,数字等宽。可绘制的有:两种方向的条形图(并列、堆积和 100% 堆积),饼图、折线图、面积图和散点图,散点图矩阵,带正态曲线的直方图,箱图,点图(正态 Q-Q 和 P-P 图、去势 Q-Q 图、离散度与水平图、残差图和载荷图)及其参考线,树状图,冰柱图和树形图。茎叶图和三维图不生成文件;它们的数据表在输出中。SVG 指定字体名称,未安装 Schibsted Grotesk 时回退到系统的无衬线字体;PNG 则内置了该字体。

终端上的文本输出与不加 --charts 时相同。图表在运行之后写入,因此无法写入的文件夹会使命令失败,但会话保持运行时保存的状态。

语法也可以写出图片。带图片子命令但不带文档的 OUTPUT EXPORT 会保存输出文档中的每个图表,在 IMAGEROOT 之后从 0 开始编号:

OUTPUT EXPORT /PNG IMAGEROOT='charts/june'.
OUTPUT EXPORT /JPG IMAGEROOT='charts/june' PERCENTSIZE=50 GRAYSCALE=YES.

第一行生成 charts/june0.png、charts/june1.png 等;文件夹必须已存在。PERCENTSIZE=100 就是 --charts 生成的 PNG,宽 1280 像素;50 则减半。可写入 PNG、JPG、BMP 和 TIF。EMF 和 EPS 会给出警告,不会写入。OUTPUT EXPORT /HTML 生成的网页将图表作为图片嵌入页面,/TEXT 则将图表保存在文本文件旁边,以该文件命名。

实时窗口会话

statscraft-gui 打开期间,会话名 gui 表示该窗口:

statscraft run -s gui -e "GET FILE='survey.sav'."
statscraft run -s gui --json job.sps
statscraft check -s gui -e "COMPUTE x = age / 10."
statscraft describe -s gui --json
  • 窗口运行语法的方式与它自己的 Run 按钮相同:表格出现在指定的输出窗口中,命令出现在日志中,数据窗口显示新数据。
  • 命令行打印的内容与文件会话相同,并带有 "session": "gui"。当运行改变了窗口会话保存的内容时,saved 为 true(参见会话);除非语法中有 SAVE,否则不会向磁盘写入任何内容。
  • 窗口在多次运行之间保存的状态与文件会话相同,保存在内存中,直到窗口关闭;describe -s gui 以同样的方式显示它。
  • 语法中的相对路径从启动 statscraft 的文件夹开始,除非窗口会话中有生效的 CD:CD 本身也从该文件夹开始,然后一直有效到下一个 CD,与文件会话相同。传给 run 的语法文件中的 INSERT 和 INCLUDE 从该文件所在的文件夹开始,与文件会话相同。一次运行会把调用方的文件夹留给窗口自己之后的运行,describe 将其显示为 directory;检查只为自身使用该文件夹。智能体运行的语法窗口从其自身文件所在的文件夹开始,没有文件时从智能体的文件夹开始。文件夹已不存在时,相对路径的文件会以各自的错误失败;不会在其他任何位置读取或写入内容。
  • 与文件会话不同,窗口在消息中用完整路径指称文件,因为它根据调用方的文件夹解析相对名称。
  • 一次只进行一个运行。窗口忙碌时,请求会等待。
  • 没有打开的窗口时,-s gui 失败并显示 “no Statscraft window is running”。打开多个窗口时,由最后启动的那个响应。

它如何连接以及为何安全:参见AI 智能体。

export

statscraft export FILE [--format xlsx|html|pdf] [--one-sheet] [--selected] [--hidden]

将打开的 statscraft-gui 窗口的输出写入文件,与其 File > Export 完全相同(参见窗口):写入指定的输出窗口,包括其插件添加到表格上的内容。

选项含义
FILE要写入的文件;相对路径从当前文件夹开始。现有文件会被替换
--format xlsx|html|pdfExcel 工作簿、网页或 PDF 文档;不加此选项时由 FILE 的扩展名决定(.xlsx、.html 或 .htm、.pdf)
--one-sheetExcel:所有表格放在一个工作表上,上下排列,而不是每个表格一个工作表
--selected只输出在输出窗口中选中的表格;没有选中任何表格时失败
--hidden也包括隐藏的项;不加此选项时只输出输出窗口中显示的内容
statscraft run -s gui -e "FREQUENCIES region."
statscraft export tables.xlsx --one-sheet
output exported to /home/me/work/tables.xlsx

没有打开的窗口、窗口没有输出或文件无法写入时,它会失败。导出会等待插件对上次运行的表格作出响应。

output

statscraft output [--document NAME] [--json]

显示打开的 statscraft-gui 窗口中某个输出窗口的内容,与用户在那里看到的一样:会话中的每个命令标题以及每个表格和图表,按顺序排列,也包括之前各次运行和其他调用方产生的内容。不加 --document 时读取指定的输出窗口;NAME 是 describe -s gui 列出的某个输出文档。它不会更改窗口中的任何内容。

第一行概括该文档,并说明窗口显示哪些类型的元素(Edit > Settings:命令标题、标题、表格、注释、图表)。随后每个标题和表格按 run 的方式打印,图表打印为其数据表;(hidden) 标记在输出中隐藏的标题或表格,(selected) 标记在输出窗口中选中的表格。

statscraft run -s gui -e "FREQUENCIES region."
statscraft output
output document Document1: 1 commands, 1 tables, 0 charts, 0 hidden, 1 selected; the window shows titles, tables, notes, charts

## FREQUENCIES

### Region of residence (selected)
...

加上 --json 时,它打印窗口的应答:document、shows(headings、titles、tables、notes、charts,各为 true 或 false)和 commands,每个命令带有 id、heading、hidden 和 items;每一项带有 id、hidden、selected,以及采用 run --json 所给形式的 table 或 chart。没有打开的窗口、窗口没有输出窗口或没有该名称的输出文档时,它会失败。

undo

statscraft undo

撤销打开的 statscraft-gui 窗口中最近一次更改了数据的运行,与其 Edit > Undo 完全相同(参见窗口):数据集恢复到该次运行之前的状态,输出保留,日志将该次运行标记为已撤销。每次调用后退一步更改,最多 10 步(文件很大时会更少,即保存的状态会占用超过 1 GB 不与当前数据共享的内存时;最近一次更改始终可以撤销)。statscraft redo 重做该运行。它打印所撤销语法的第一行:

statscraft run -s gui -e "COMPUTE total = q1 + q2."
statscraft undo
undone: COMPUTE total = q1 + q2.

没有打开的窗口,或没有可撤销的数据更改时,它会失败。文件会话没有撤销功能。

redo

statscraft redo

在打开的 statscraft-gui 窗口中重做最近一次 statscraft undo 所撤销的运行,与其 Edit > Redo 相同:数据集恢复到该次撤销之前的状态,日志不再将该次运行标记为已撤销。每次调用前进一次运行,最多到所撤销的运行为止。撤销之后运行一个更改数据的命令会结束重做,之后的任何更改也是如此。它打印所重做语法的第一行:

statscraft undo
statscraft redo
redone: COMPUTE total = q1 + q2.

没有打开的窗口,或没有可重做的内容时,它会失败。

mcp

statscraft mcp 通过标准输入和标准输出将 describe、help、check 和 run 作为 MCP 工具提供,供启动本地 MCP 服务器的智能体应用使用。它一直运行,直到应用关闭连接。MCP 服务器列出了这些工具,并说明其会话保存在何处。

code

statscraft code FILE runs a JavaScript async arrow function as the MCP tool run_code does (Code mode): every MCP tool is a function of the object statscraft, with the same arguments, the same default session work and the same file sessions as statscraft mcp. Give - for FILE to read the script from standard input.

It prints what the function returns as pretty JSON and writes the console.log lines to standard error. With --json it prints the whole reply instead: ok, value, logs and error. When the script throws or reaches a limit, it writes error: line L, column C: MESSAGE to standard error and exits with 1.

statscraft code count.js

JSON 输出

run、check 和 describe 加上 --json 时打印格式化的 JSON。plan 和 db 始终打印一行 JSON。

运行结果

statscraft run -s demo --json -e "COMPUTE spend_year = monthly_spend * 12. 后接第二行 FREQUENCIES VARIABLES=gender.",打印如下内容(此处表格行已缩短):

{
  "ok": true,
  "session": "demo",
  "commands": [
    {
      "name": "COMPUTE",
      "first_line": 1,
      "last_line": 1,
      "tables": [],
      "warnings": []
    },
    {
      "name": "FREQUENCIES",
      "first_line": 2,
      "last_line": 2,
      "tables": [
        {
          "title": "Gender",
          "row_headers": 3,
          "columns": ["Category", "Value", "Label", "Frequency", "Percent", "Valid Percent", "Cumulative Percent"],
          "column_groups": [[], [], [], [], [], [], []],
          "rows": [
            ["valid", 1.0, "Male", 106.0, 53.0, 53.0, 53.0],
            ["total", null, null, 200.0, 100.0, null, null]
          ]
        }
      ],
      "warnings": []
    }
  ],
  "changes": {
    "cases_before": 200,
    "cases_after": 200,
    "variables_added": ["spend_year"],
    "variables_removed": [],
    "variables_changed": []
  },
  "dataset": [200, 21],
  "saved": true
}
字段含义
oktrue
session会话名称;不加 -s 时不出现
trail本次运行的语法保存的位置:会话的 syntax.sps 的绝对路径,对于 gui 则是语法窗口,例如 syntax window Agent。没有会话时以及对于 check 不出现
commands每个已运行的命令一项,按顺序排列,带有其在源代码中的第一行和最后一行
commands[].tables该命令的表格
commands[].charts该命令的图表(参见图表);没有生成图表时不出现
commands[].warnings命令在未失败的情况下与要求不同的处理,例如 "no statistics for string variables: plan"
changes之前和之后的个案数(没有数据集时为 null),以及新增、删除和更改的变量名称。变量的字典条目或任何值有所不同时,即视为已更改
dataset运行后活动数据集的 [cases, variables];没有活动数据集时不出现
saved会话文件已写入时为 true(对于 gui:运行改变了窗口会话时)。没有会话时以及对于 check 始终为 false

表格:

字段含义
title表格标题
row_headers前面有多少列是行标签
columns每列最内层的表头
column_groups每列上方的各级表头,从最外层开始;单层表头时为空列表
rows单元格:数值、文本,或表示空单元格的 null。数值为原始值,未经舍入
formats可选,结构与 rows 相同:每个单元格的显示格式,例如 "PCT5.1",或 ""
caption可选,表格下方的文字

一个带两级表头的自定义表格,来自 CTABLES /TABLE region [COUNT, COLPCT.COUNT PCT5.1] BY gender.(仅第一行,已缩短):

{
  "title": "Custom Tables",
  "row_headers": 2,
  "columns": ["", "", "Count", "Column %", "Count", "Column %", "Count", "Column %"],
  "column_groups": [["", ""], ["", ""], ["Gender", "Male"], ["Gender", "Male"], ["Gender", "Female"], ...],
  "rows": [["Region of residence", "North", 23.0, 21.69811320754717, 11.0, 12.5, 0.0, 0.0], ...],
  "formats": [["", "", "F40.0", "PCT5.1", "F40.0", "PCT5.1", "F40.0", "PCT5.1"], ...]
}

图表

GRAPH、FREQUENCIES(BARCHART、PIECHART、HISTOGRAM)、CROSSTABS(BARCHART)、EXAMINE(PLOT)、ONEWAY(PLOT MEANS)、REGRESSION(RESIDUALS、SCATTERPLOT、PARTIALPLOT)、LOGISTIC REGRESSION(CLASSPLOT)、UNIANOVA 和 GLM(PLOT)、DISCRIMINANT(PLOT)、FACTOR(PLOT)、CLUSTER(PLOT)以及 TREE(树形图,PLOT)会生成图表。图表就是数据:它的类型、标签和数值,不含任何颜色或布局信息。标签与表格一样遵循 SET TVARS、TNUMBERS 和 OVARS。statscraft run --json -e "..." 配合 CROSSTABS /TABLES=region BY gender /BARCHART. 得到(已缩短):

{
  "kind": "bar",
  "tier": "presentation",
  "orientation": "vertical",
  "grouping": "clustered",
  "title": "Region of residence by Gender",
  "category_axis": { "title": "Region of residence", "format": "F1.0", "variable": "region" },
  "value_axis": { "title": "Count", "format": "F8.0" },
  "legend": "Gender",
  "categories": [
    { "label": "North", "value": 1.0 },
    { "label": "South", "value": 2.0 }
  ],
  "series": [
    { "name": "Male", "statistic": "count", "variable": "gender", "value": 1.0, "values": [23.0, 23.0] },
    { "name": "Female", "statistic": "count", "variable": "gender", "value": 2.0, "values": [11.0, 23.0] }
  ]
}
字段含义
kindbar、pie、line、area、error_bar(每个值一个点,带误差条)、range_bar(每对系列之间的浮动条形)、drop_line 和 high_low(各点,并有一条线从每个类别的最低值连到最高值;对于 high_low,第三个系列为收盘值)、difference(两条线,其间区域加阴影)、scatter、dot(点图:点与 scatter 相同,说明文字标为点图)、histogram、boxplot、stem_leaf、normal_qq、detrended_normal_qq、normal_pp、spread_level、dendrogram、icicle、tree_diagram 或 territorial_map
tierpresentation(办公软件可作为可编辑图表保存的图表)或 statistical(精确绘制的图,例如直方图)
orientationvertical(类别沿底部排列)或 horizontal;饼图时不出现
groupingclustered、stacked 或 percent(100% 堆积);仅用于条形、线和面积
title, subtitle, footnote标题(与同一命令的表格标题相同),其下方的可选一行(GRAPH /SUBTITLE),以及可选的注释,例如直方图的均值、标准差和 N
category_axis, value_axis各自带有 title、其数值的显示格式 format、语法设定了坐标轴上限时的 maximum,以及它所显示的变量 variable
legend区分各系列的依据,例如列变量;只有一个系列时不出现
categories按绘制顺序:label,它所代表的值 value(全部为缺失值的扇区为 null),包含缺失值时的 missing,以及直方图分组的 bin([from, to]),分组包含其下界但不包含上界
series各自带有 name,其数值所代表的统计量 statistic(count,设置了权重时为加权计数,percent、mean 或 value),它所代表的 variable 和 value,以及 values,每个类别一个数值
normal直方图的正态曲线:mean、std_dev 和 total;它在 x 处的高度等于 total 乘以分组宽度再乘以正态密度
error_bars带误差条的条形、线和点,例如带 ERRORBAR 的轮廓图或 GRAPH ERRORBAR 图表:label 说明误差条的范围(95% CI、2 SE),margins 为每个系列给出一个列表,列出其在每个类别处误差条的半长(误差条从值减去半长延伸到值加上半长;没有误差条的系列为空列表,某个值没有误差条时为 null);lower 只在误差条向下延伸的长度小于向上延伸的长度时出现(中位数的区间),以同样方式列出向下的长度,此时 margins 为向上的长度
second_axis条形图右侧的第二个数值坐标轴(title、format、maximum),用于其最后一个系列,该系列绘制为条形上方的一条线,例如 GRAPH PARETO 图表的累积百分比
plot除直方图以外的统计图的数据,按其 shape 区分;此时 categories 和 series 为空,类别坐标轴为水平轴,数值坐标轴为垂直轴

plot 的各种形状:

  • boxes:boxes,每个带有 label、group(箱体分组时所属的簇)、n、lower_whisker、lower_hinge、median、upper_hinge、upper_whisker,以及标记的个案 outliers 和 extremes(每个为一个 value 及其个案标签 case)。
  • stem_leaf:stem_width、each_leaf(每片叶的个案数)、lines(每行包含 frequency、显示的 stem 以及以数字表示的 leaves),以及 low_extremes、high_extremes(frequency 和 bound)。
  • points:groups,每个带有 name 和 points(x、y,可选的 z 和 label);lines,即直的参考线 y = intercept + slope x;点有深度时还有 z_axis。Q-Q 图、P-P 图、离散度与水平图、散点图、偏回归图和载荷图使用此形状。
  • matrix:variables,按顺序排列的坐标轴(每个带有 title 和 format),以及 groups,每个带有 name 和 cases,每个个案带有按变量顺序排列的 values(缺失处为 null)和可选的 label。GRAPH SCATTERPLOT(MATRIX) 使用此形状,类型为 scatter。
  • merges:items(个案标签)、order(各项的排列,使分支不交叉)、merges(每个都在高度 height 处将簇 right 合并到簇 left 中,两者都以项的索引命名,rescaled 为 1 到 25 的重新标度值),以及冰柱图的 solutions,即它所显示的簇数。
  • tree:nodes,每个带有 id、parent、通向它的分割条件 split,以及由名称和值对构成的 statistics。
  • regions:regions,每个带有 name、其中心 center([x, y],例如组质心)和 vertices,即其凸多边形按环绕顺序排列的各个顶点(区域为空时为空)。DISCRIMINANT 的区域图使用此形状。

加上 --vega-lite 时,每个图表还有一个成员 vega_lite:一个数值内联的 Vega-Lite v5 规范,任何 Vega-Lite 查看器都能直接绘制。在 Markdown 输出中,该规范作为 json 代码块跟在图表的数据表之后。SPLIT FILE 为每个拆分组生成一个图表,组名写在标题中。

作为输入的图表

Statscraft 能以其写出的形式读回图表,因此智能体或脚本可以将任何过程都不生成的图表放入输出。该图表的绘制、保存和导出与其他图表一样:在窗口的输出中,以及 OUTPUT SAVE、OUTPUT EXPORT、Copy,和用 Open in 在办公软件中打开。

statscraft chart sales.json -s work
statscraft chart sales.json -s gui
cat sales.json | statscraft chart - --json

statscraft chart FILE(或用 - 表示标准输入)与 run 一样接受 -s、--json、--vega-lite、--xlsx 和 --charts。它运行语法 BEGIN CHART(Statscraft 的扩展),文件的 JSON 位于 BEGIN CHART 和 END CHART 之间,二者各占一行;同样的块在任何语法文件中都有效,因此同一次运行中的 OUTPUT EXPORT 会把该图表写出。MCP 工具 add_chart 的作用相同。参见 BEGIN CHART。

JSON 采用以下两种形式之一。

上面的图表 JSON,即 --json 写出的形式。一次运行产生的图表读回后是同一个图表,因此最简单的做法是取某个过程的图表加以修改。可以给出 "version": 1;更高的版本会被拒绝。--vega-lite 添加的成员 vega_lite 会被忽略。图表没有的字段会报错,因此拼错的字段不会悄然丢失;值为 null、false 或空的字段视为省略。kind、tier、title、category_axis 和 value_axis(各带一个 title)、categories 和 series(各带 name、statistic 和 values)是必需的。没有数值的地方可以为 null。统计图在 plot 中给出数据,形状为 points(类型 scatter、normal_qq、detrended_normal_qq、normal_pp、qq、detrended_qq、pp、detrended_pp、roc、spread_level)或 boxes(类型 boxplot);其他形状只能由各自的过程生成。

单个视图的 Vega-Lite 规范,即能清晰对应到 Statscraft 图表的部分:

标记编码结果
barx 和 y,其中一个为 quantitative;可选 color,以及作用于 color 字段的 xOffset 或 yOffset条形图:y 存放数值时为垂直,x 存放数值时为水平。有 color 时条形堆积,与 Vega-Lite 相同;有偏移时并列;stack: "normalize" 将其堆积到 100%
linex(类别)和 y(quantitative),可选 color折线图,每种颜色一条线
area同上面积图;有 color 时堆积,使用 stack: "normalize" 时堆积到 100%
pointx 和 y,均为 quantitative,可选 color散点图,每种颜色一组;缺少任一数值的行会被省略
arctheta(quantitative)和 color饼图,每种颜色一个扇区
  • 各行以对象形式内联在 data.values 中。每行给出一个值:同一类别(和颜色)出现两次会报错,因为不进行任何汇总。
  • 通道接受 field、type(quantitative、nominal、ordinal 或 temporal;color 和偏移默认为 nominal)、title 和 sort:"ascending"(默认,与 Vega-Lite 相同)、"descending"、表示按数据顺序的 null,或一个排在最前的值列表。axis、legend 和 scale 会被接受但不起作用;width、height、config 以及其他只设置图表外观的成员,还有 mark 中除 type 之外的属性也是如此。
  • title 是一个字符串,或一个带有 text 和 subtitle 的对象。没有标题时,图表根据坐标轴标题命名为 “values by categories”。坐标轴标题是通道的 title,否则为其字段名。
  • 以下内容会被拒绝,并给出指明不支持之处的消息:其他标记,size 或 shape 等编码,aggregate、bin、timeUnit,固定的 value 或 datum,transform、layer、facet、repeat 和各种拼接,params,来自 url 或按 name 引用的数据,以及 Vega(而非 Vega-Lite)模式。

两种形式的限制:最多 100 个系列、3000 个类别、100000 个值(系列数乘以类别数,或点数、行数),字符串最长 1000 个字符,JSON 文本最大 16 MB。各部分不相容的图表,例如某个系列的值少于类别数,会在绘制之前被拒绝。

错误

任何失败时,--json 都会在标准输出上打印以下内容,退出代码为 1:

{"ok":false,"errors":[{"kind":"syntax","message":"unexpected end of command","line":1,"column":18,"expected":["a value","a variable","a function","'('"]}],"saved":false}
字段含义
kindsyntax(文本无法解析)、run(命令在数据上失败)、usage(选项或参数错误)、session 或 file(读取或写入失败)
message出了什么问题
line, column位置,从 1 开始计数。语法错误两者都有;运行错误给出命令的第一行
command对于运行错误,失败的命令
expected对于语法错误,在该位置有效的内容
hint建议,例如 "did you mean FREQUENCIES?"

更多示例:

{"ok":false,"errors":[{"kind":"run","message":"unknown variable agee","command":"FREQUENCIES","line":2}],"saved":false}
{"ok":false,"errors":[{"kind":"syntax","message":"unknown command FREQUENCIS","line":1,"column":1,"hint":"did you mean FREQUENCIES?"}],"saved":false}

不加 --json 时,同样的错误以 error: line 1, column 18: unexpected end of command; expected: a value, a variable, a function, '(' 的形式输出到标准错误。

警告

警告不会使运行失败。它们位于运行结果的 commands[].warnings 中,在文本输出中显示为:

warning: line 1: DESCRIPTIVES: no statistics for string variables: plan

字典

对于带有两个多重响应集的加权调查文件,statscraft describe FILE --json 打印(已缩短):

{
  "encoding": "UTF-8",
  "compression": "bytecode",
  "case_count": 200,
  "variable_count": 19,
  "file_label": "Statscraft synthetic customer survey",
  "weight_variable": "weight",
  "multiple_response_sets": [
    {"name": "$q5", "type": "dichotomy", "label": "Q5. Contact channels used", "counted_value": 1,
     "variables": ["q5_1", "q5_2", "q5_3", "q5_4", "q5_5"]},
    {"name": "$q6", "type": "category", "label": "Q6. Other providers mentioned", "counted_value": null,
     "variables": ["q6_mention1", "q6_mention2", "q6_mention3"]}
  ],
  "variables": [
    {
      "name": "q2_recommend",
      "type": "numeric",
      "label": "Q2. How likely are you to recommend us to a friend or colleague?",
      "format": "F2.0",
      "measure": "scale",
      "value_labels": {"0": "Not at all likely", "10": "Extremely likely", "97": "Not applicable", "98": "Don't know", "99": "Refused"},
      "missing_values": [],
      "missing_range": [97.0, 99.0],
      "n_valid": 176,
      "n_system_missing": 0,
      "n_user_missing": 24
    },
    {
      "name": "plan",
      "type": "string",
      "width": 10,
      "label": "Current subscription plan",
      "format": "A10",
      "measure": "nominal",
      "value_labels": {},
      "missing_values": [],
      "missing_range": null,
      "n_valid": 200,
      "n_system_missing": 0,
      "n_user_missing": 0
    }
  ]
}
字段含义
encoding, compression文件的编码和压缩方式(压缩方式为 none、bytecode 或 zlib)
file_label文件没有文件标签时不出现
weight_variable权重变量,或 null
multiple_response_sets没有多重响应集时不出现
variables[].typenumeric 或 string;字符串还有以字节为单位的 width
variables[].measurenominal、ordinal、scale 或 unknown
variables[].value_labels值(文本形式)到标签的映射
variables[].missing_values, missing_range用户缺失值:最多三个值,或一个 [low, high] 范围
variables[].numbers_as_text适用于所有值都是普通数字的字符串变量:即 ALTER TYPE name (format). 会给它的格式,例如 F7.2。其他情况下不出现;带前导零的值(例如 01234 这样的代码)、带货币符号或指数的值都不是普通数字,只要有一个这样的值,就不会提供此项。空白值会变为系统缺失值。小数点符号由会话的 SET DECIMAL 决定
n_valid, n_system_missing, n_user_missing基于所有个案的计数

Statscraft 0.61.0, release v0.61.0

数据库

本页面向在数据库中保存调查数据的用户。statscraft db 将数据集存入 SQLite、PostgreSQL、MySQL、MariaDB 或 Dolt 并读回,statscraft plan 则对已存储的数据集就地应用重新编码和标签。两者都遵循 OpenStatSpec 规范,因此遵循该规范的其他程序可以读取相同的表。

用示例文件快速往返一次:

statscraft db export survey.sav --sqlite study.db
statscraft plan -e "RECODE satisfaction (9 = SYSMIS)." --sqlite study.db --name survey --apply
statscraft db import --sqlite study.db --name survey --out back.sav

第一行将文件存入一个新的 SQLite 数据库,第二行在数据库中对一个变量重新编码,第三行将结果写入一个新的 .sav 文件。

转换计划:plan

statscraft plan [FILE | - | -e TEXT] (--input-schema FILE | -s SESSION | --sqlite DB --name DATASET [--apply [--actor NAME]])
                [--profile 0.1|0.2|0.3] [--alias NAME]

plan 把语言中一个有限的子集转换为 OpenStatSpec 转换计划(Transformation Plan):输出一行规范化 JSON,包含计划本身、其 SHA-256 plan_hash 以及语法的 source_hash;或者输出一个错误,带有稳定的 code、line 和 column。

选项含义
--input-schema FILE形如 {"variables": [{"name": "q1", "storage_kind": "numeric"}]} 的 JSON
-s, --session NAME从会话的数据集获取输入模式
--sqlite DB --name DATASET从 OpenStatSpec SQLite 数据库中的数据集获取输入模式
--apply与 --sqlite 一起使用时,就地将计划应用到该数据集,在一个事务中完成,并写入一条审计行
--actor NAME应用计划的人,记入审计行;默认为 $USER
--profile前端配置档,默认为 0.3
--alias计划中输入数据集的名称,默认为 input

配置档 0.1 接受 RECODE、VARIABLE LABELS 和 VALUE LABELS;0.2 增加了使用单个值和简单比较的 COMPUTE 与 IF,以及 FORMATS、VARIABLE LEVEL 和 EXECUTE;0.3 增加了注释、TO 列表、NE 和 NOT、LOWEST 与 HIGHEST 范围以及 ADD VALUE LABELS。其他一切都会被拒绝,即使 run 接受它们。当 schema.json 包含 {"variables": [{"name": "q1", "storage_kind": "numeric"}, {"name": "q2", "storage_kind": "numeric"}]} 时:

statscraft plan -e "RECODE q1 (1 = 0)." --input-schema schema.json --profile 0.1
statscraft plan -s demo -e "RECODE satisfaction (9 = SYSMIS)."
statscraft plan -e "FREQUENCIES q1." --input-schema schema.json

最后一条命令打印 {"error":{...,"message":"FREQUENCIES is not supported by frontend profile 0.3",...},"ok":false,...},其中的 code 是该配置档表示不支持命令的代码,退出代码为 1。

存储和读取数据集:db

statscraft db export survey.sav --sqlite study.db [--name survey]   store a dataset in SQLite
statscraft db export survey.sav --postgres URL                      or in PostgreSQL
statscraft db export survey.sav --mysql URL                         or in MySQL or MariaDB
statscraft db export survey.sav --dolt URL                          or in Dolt
statscraft db export -s work --sqlite study.db --name work          store a session's dataset
statscraft db import --sqlite study.db --name survey --out back.sav read it back into a file
statscraft db import --sqlite study.db --name survey -s work        or into a session
statscraft db capabilities                                          versions and limits per database
statscraft plan job.sps --sqlite study.db --name survey --apply     apply syntax to it in place

db 按照 OpenStatSpec 的 SAV/ZSAV 配置档 1.0 及其 SQL 方言配置档的规定存储数据集。

  • 一个 data_<name> 表保存个案:__case_ordinal(按个案顺序为 1、2、3……)以及每个变量一列,按变量顺序排列。
  • 数字为 binary64,系统缺失值存为 NULL。字符串为文本,从不为 NULL。用户缺失值代码作为值保留,日期作为数字保留。
  • 数据字典存入目录表:标签、值标签、缺失值、格式、测量级别、角色、显示设置、属性、文档、权重变量和多重响应集。
  • 不是纯 ASCII 的变量名会得到生成的列名(v<position>);目录表负责将其映射回原名。
  • 该数据库专供 OpenStatSpec 使用。export 在新的或空的数据库中建立目录表,并拒绝包含其他任何内容的数据库。
选项含义
--sqlite FILE, --postgres URL, --mysql URL, --dolt URL数据库;参见数据库
--name数据集名称:ASCII 字母、数字和 _。对于 export,默认为文件名或会话名
--out FILEimport 写入这个 .sav 或 .zsav 文件
-s, --session NAMEexport 读取该会话的数据集,import 则替换它
--allow-loss当目录表中有数据集无法保留的项目时,import 仍继续执行

每条命令打印一行 JSON,例如 {"case_count":300,"dataset":"survey","dataset_id":"...","ok":true,"table":"data_survey","variable_count":18},或者打印 {"ok":false,"error":{"code":...,"message":...}} 并返回退出代码 1。

statscraft db export survey.sav --sqlite study.db
statscraft db export -s demo --sqlite study.db --name work
statscraft plan -e "RECODE satisfaction (9 = SYSMIS)." --sqlite study.db --name survey --apply --actor demo
statscraft db import --sqlite study.db --name survey --out back.sav
statscraft db import --sqlite study.db --name work -s fromdb

Reading from syntax

Syntax reads a stored dataset as the active dataset with GET DATA /TYPE=OPENSTATSPEC, so run, the window and the MCP server reach the same databases:

GET DATA /TYPE=OPENSTATSPEC /DATABASE=SQLITE 'study.db' /DATASET=survey_basic.
GET DATA /TYPE=OPENSTATSPEC /DATABASE=POSTGRES 'postgres://analyst@db.example.org/study' /DATASET=survey_basic.

It reads like db import: /ALLOWLOSS=YES stands for --allow-loss, and the read is logged in the catalog’s operation table, except on Dolt. On Dolt a table shows the branch and the HEAD commit that were read, the values plan --apply later expects, and a warning says when the working set holds uncommitted changes. Syntax is kept in trails and syntax windows, so a URL with a password in it is refused; set STATSCRAFT_DB_PASSWORD in the environment of the program that runs the syntax. The window reads it from its own environment, so start the window where the variable is set. statscraft check and the MCP tool check_syntax read without logging.

写入和读取

  • 写入前,预检会根据配置档和服务器设置检查列数上限、标识符、值的大小和行的大小。SQLite 拒绝 NaN 和负零,因为它无法保存这两种值。
  • 失败时不会留下任何表或数据集行,只留下失败的操作及其诊断信息。
  • 各行在同一事务中批量写入:
    • PostgreSQL 通过二进制格式的 COPY 接收;
    • MySQL 和 MariaDB 使用预编译的多行 INSERT,每条最多 4 MiB,且不超过 max_allowed_packet;
    • Dolt 使用由字面值组成的多行 INSERT,每条最多 256 KiB,且不超过 max_allowed_packet;
    • SQLite 对每个个案使用一条预编译的 INSERT。
  • 读取时,行从服务器以流的方式读入数据集,而不是先保存整个结果。
  • 如果数据集的目录表中有 Statscraft 无法保留的项目(数据集属性、变量集、不同于打印格式的写入格式),读取会失败,除非指定了 --allow-loss。此时这些损失会在输出中列出。

支持的数据库

SQLitePostgreSQLMySQL, MariaDBDolt
选项--sqlite FILE--postgres postgres://user@host:port/db[?schema=NAME]--mysql mysql://user@host:port/db--dolt mysql://user@host:port/db
目录表所在位置整个文件模式 NAME(默认为 openstatspec)数据库 db数据库 db,位于会话所在的分支上
服务器版本内置的 SQLite17.x、18.x,UTF8 编码MySQL 8.4.x、9.7.x;MariaDB 11.4.x、11.8.x、12.3.x;16 KiB InnoDB 页读取 2.2.2 起的 2.2.x;写入 2.2.2 和 2.2.3
列数(包括 __case_ordinal)2,0001,6001,0174,097
数字REAL;拒绝 NaN 和负零DOUBLE PRECISION,保留所有位模式DOUBLE;拒绝 NaN、无穷大和负零DOUBLE;拒绝 NaN、无穷大和负零
文本TEXT NOT NULLTEXT NOT NULL;拒绝 U+0000TEXT NOT NULL,二进制排序规则,最多 65,535 字节LONGTEXT NOT NULL
行长度上限8,160 字节的堆元组(NULL 不占空间)8,126 字节的 InnoDB 记录:每个数字 8 字节,每个字符串 41 字节(MySQL)或 21 字节(MariaDB);每条 INSERT 不超过 max_allowed_packet表定义小于 65,504 字节:每个数字 8 字节,每个字符串 20 字节
标识符255 字节max_identifier_length(63 字节)64 个字符64 个字符
plan --apply 中的新变量支持,在同一事务中支持,在同一事务中不支持:在任何更改之前报 schema_change_not_atomic不支持:schema_change_not_atomic

MySQL、MariaDB 和 Dolt 会隐式提交 DDL。因此 export 先创建表,然后在一个事务中写入行和目录表,如果失败则再删除该表。会创建变量的计划会在任何更改发生前被拒绝;请先单独一步创建该列及其目录表中的变量。

数据库产品由服务器对自身的报告决定,而不是由协议决定:--mysql 拒绝 Dolt 服务器,--dolt 拒绝 MySQL 和 MariaDB。

Dolt

  • Statscraft 从不执行提交、创建分支、合并或重置。
  • db export 将其更改留在工作集中,由您来提交。
  • db import 和 plan 的输入模式完全不写入任何内容(这是 OpenStatSpec 的 Database I/O Execution Policy v1,由 db capabilities 声明)。因此,允许的损失在输出中报告,而不是记入目录表。
  • plan --apply 需要 --expected-branch 和 --expected-head。会话必须位于该分支的该提交上,且工作集干净;应用完成时,该分支必须仍指向该提交。审计行会记录这两项,而更改保持未提交状态。
  • 会话所在的分支是数据库的默认分支,或者是 URL 中以 db/branch 形式指定的分支。

密码和 TLS

不含密码的 URL 从环境变量 STATSCRAFT_DB_PASSWORD 获取密码。密码从不打印。

除非 URL 要求使用 TLS,否则连接使用普通 TCP。TLS 总会验证服务器的证书链:提供了 CA 文件时以该文件为准,否则以内置的 Mozilla 根证书为准。除非模式另有规定,它还会检查主机名。Statscraft 从不建立未经验证的 TLS 连接,并拒绝会退回到普通 TCP 的模式(prefer、allow、PREFERRED)。

statscraft db export survey.sav --postgres "postgres://analyst@db.example.org/study?sslmode=verify-full"
statscraft db export survey.sav --postgres "postgres://analyst@10.0.0.5/study?sslmode=verify-ca&sslrootcert=/etc/ssl/study-ca.pem"
statscraft db export survey.sav --mysql "mysql://analyst@db.example.org/study?ssl-mode=VERIFY_IDENTITY&ssl-ca=/etc/ssl/study-ca.pem"
PostgreSQL sslmodeMySQL、MariaDB、Dolt ssl-mode连接
未指定、disable未指定、DISABLED普通 TCP
verify-full, requireVERIFY_IDENTITY, REQUIREDTLS;检查证书链和主机名
verify-caVERIFY_CATLS;检查证书链,不检查主机名
  • sslrootcert=FILE(PostgreSQL)或 ssl-ca=FILE(MySQL、MariaDB、Dolt)指定一个 PEM 文件,其中包含要信任的 CA 证书,用于证书来自私有 CA 的服务器。
  • 只有 CA 文件而未指定模式时,等同于 verify-full。
  • 有 CA 文件时,PostgreSQL 只信任该文件;MySQL 客户端还会同时信任内置的根证书。
  • require 和 REQUIRED 始终检查证书链和主机名。

就地应用计划

plan --name DATASET with a database option takes the input schema from that dataset. With --apply it then applies the plan to the same table in one transaction: direct UPDATEs, ALTER TABLE ... ADD COLUMN for new variables, catalog updates and one audit row in transformation_apply (plan and source hashes, actor, operation count). Nothing is copied, and on any error nothing changes. --actor names who applies the plan (default $USER). The MCP tool apply_plan does the same for an agent, with actor required to apply and a URL with a password refused; see Editing a dataset in a database.

Statscraft 0.61.0, release v0.61.0

面向 AI 智能体的 Statscraft

Statscraft 的设计使拥有 shell 的 AI 智能体可以完成分析工作:一切都是语法,每个结果都是 JSON,每个错误都有行号和列号,会话在各步骤之间保留数据。本页说明智能体应如何工作,并提供一段可以粘贴到您的智能体中的指令。

能运行 MCP 服务器的智能体应用可以通过工具而不是 shell 使用同样的循环:参见 MCP 服务器。运行一次 statscraft connect,即可将其添加到您计算机上的智能体中;连接您的 AI 智能体说明了它会更改什么以及如何撤销。

工作循环

  1. 查看数据。 statscraft describe FILE --json 给出数据字典:变量名、类型、标签、值标签、缺失值、有效计数、权重变量和多重响应集。编写语法前先阅读它,确保名称和代码正确。
  2. 查阅语法。 statscraft help 列出支持的命令;statscraft help COMMAND 给出语法、规则和一个示例。只使用帮助中显示的内容。帮助中未列出的命令会失败,并给出清楚的错误。
  3. 将语法写入文件(job.sps),每条命令占一行或一个块,每条都以句点结尾。
  4. 检查语法。 statscraft check -s NAME --json job.sps 解析每条命令,并在会话数据的副本上运行,因此还能发现未知变量和类型错误,而且不写入任何内容。
  5. 分段运行。 statscraft run -s NAME --json --lines FIRST-LAST job.sps 运行这些行中的命令,并把结果保留在会话中。下一个范围在此基础上继续。行号仍为文件中的行号。会话在多次运行之间保留数据、设置、宏和命名数据集,就像窗口一样(会话)。statscraft describe -s NAME --json 在 session 下显示保留的状态。
  6. 读取 JSON。 ok 表示运行是否成功。changes 列出新增、更改和删除的变量,以及运行前后的个案数;dataset 给出数据集大小;commands[].tables 包含带原始数字的结果;commands[].charts 包含命令生成的图表,每个图表以其类型、标签和数字表示;commands[].warnings 指出命令在何处的行为与要求不同。
  7. 在错误指向的位置修正。 失败时,errors[] 给出 kind、message、line,对于语法错误还给出 column、expected,通常还有 hint。修正那一行,然后再次运行同一范围。失败的运行不保存任何内容(包括设置),因此重试从相同状态开始。

一个简短的会话:

statscraft describe survey.sav --json
statscraft help RECODE
statscraft check -s work --json job.sps
statscraft run -s work --json --lines 1-1 job.sps
statscraft run -s work --json --lines 4-6 job.sps
statscraft run -s work --json -e "FREQUENCIES VARIABLES=age_group."
statscraft describe -s work --json

语法错误会告诉智能体出错的位置和内容:

{"ok":false,"errors":[{"kind":"syntax","message":"unexpected end of command","line":1,"column":18,"expected":["a value","a variable","a function","'('"]}],"saved":false}

拼错的命令会附带建议:

{"ok":false,"errors":[{"kind":"syntax","message":"unknown command FREQUENCIS","line":1,"column":1,"hint":"did you mean FREQUENCIES?"}],"saved":false}

所有字段参见命令行。

良好习惯:

  • 每一步都使用 --json,并先读取 ok 字段;成功时退出代码为 0,失败时为 1。
  • 将整个分析放在一个 .sps 文件中,并按行范围运行,这样该文件就是所做工作的记录,还可以用 statscraft run job.sps 从头再次运行。
  • 要重新开始,请使用新的会话名称,或删除 .statscraft/sessions/NAME/。
  • JSON 中的数字是原始值。只在报告时再进行舍入。
  • 当用户需要 Excel 格式的表格时,在运行时添加 --xlsx tables.xlsx。
  • 要交付输出本身,在运行的最后加上 OUTPUT SAVE OUTFILE='results.scout'.:用户可以在窗口中通过 File > Open output 打开它。用户交给您的 .scout 文件是纯 JSON:直接读取即可,其中每条命令都附有其语法和表格(输出文件)。要将其转换为工作簿或网页,请运行 OUTPUT OPEN FILE='results.scout'. 和 OUTPUT EXPORT。
  • 需要展示图表时添加 --vega-lite:这样每个图表都会附带一个 Vega-Lite 规范,数字内嵌其中,可直接用于任何 Vega-Lite 查看器。不要根据自己计算的数字绘制图表。

A dataset stored in an OpenStatSpec database is edited in place with statscraft plan and a database, or the MCP tool apply_plan: preview the plan first, then apply it with actor naming who makes the change, then read the dataset back with statscraft db import instead of assuming the result. On Dolt, put the edits of one step into one plan, since an apply needs a clean working set and never commits. See plan and Editing a dataset in a database.

When one step depends on the numbers of another, or a run returns far more than you need, write the steps as one JavaScript function and run it with statscraft code (or the MCP tool run_code): it calls the same tools, keeps only what you return, and still leaves every run’s syntax in the session’s trail. See Code mode.

在打开的窗口中工作

当用户打开了 Statscraft 窗口时,智能体可以在窗口中工作,而不使用文件会话:会话名称 gui 会把语法发送到窗口,窗口像点击自己的 Run 按钮一样运行它。用户会看到每个表格出现在输出窗口中,每条命令出现在日志中,并且可以在智能体的两次运行之间继续在窗口中工作。实时窗口会话说明了其工作方式。

由于用户也可能在窗口中更改数据,智能体在依赖先前看到的名称或计数之前,应再次运行 statscraft describe -s gui --json。

每次成功的运行都会把其语法留在窗口中:语法被添加到名为 Agent 的语法窗口,位于一行带时间的注释之下(* Agent 14:32.)。该窗口在第一次运行时打开;用户关闭它后,下次运行时会再次打开。用户可以阅读所做的工作、修改它、按 Ctrl+Enter 运行并保存。失败的运行不添加任何内容。JSON 中的 trail 给出该窗口的名称。文件会话也会这样做,写入其文件夹中的 syntax.sps,每行注释带有日期,trail 给出该文件的路径。

智能体还可以通过 MCP 服务器读取、编辑、运行和保存用户的语法窗口;参见 MCP 服务器。当用户要求修正或解释其语法时,请读取该窗口,说明您打算如何修改,在窗口中编辑并从那里运行,这样修正会保留在用户的文件中。

窗口可以同时包含多个数据集和输出文档。在 session 下,describe 按用户看到的样子列出它们:active_dataset 是所有命令作用的数据集,datasets 列出每个打开的数据集及其大小(从窗口打开的文件会得到名称 DataSet1、DataSet2 等),output_documents 列出输出文档,designated_output 是接收后续表格的文档。运行 JSON 中的每条命令都在 commands[].document 中给出其文档。要处理另一个数据集,请运行 DATASET ACTIVATE name.;要把表格发送到其他位置,请运行 OUTPUT NEW NAME=name. 或 OUTPUT ACTIVATE name.。窗口忙碌时,智能体发起的运行会等待,待窗口空闲后再运行。

粘贴到智能体中的指令

You can analyze data with Statscraft, a statistics program driven by the established
statistics command syntax (COMPUTE, RECODE, FREQUENCIES, CTABLES and so on). Use the `statscraft` command line in the shell.

- Start with `statscraft describe <file> --json` to learn the variables, labels and missing values.
- Look up syntax with `statscraft help` and `statscraft help <COMMAND>`. Use only commands and
  options that the help lists.
- Write the syntax to a .sps file. Before running, check it:
  `statscraft check -s work --json <file>.sps`.
- Run it in steps that keep the data between them:
  `statscraft run -s work --json --lines FIRST-LAST <file>.sps`, or
  `statscraft run -s work --json -e "<syntax>"` for a single command. The session keeps data,
  settings, macros and named datasets between runs; `statscraft describe -s work --json` shows them.
- Read the JSON. If "ok" is false, fix the line and column given in "errors" (use "expected" and
  "hint") and run the same lines again; a failed run changes nothing. Read "warnings" of every
  command and "changes" to confirm what happened to the data.
- If I have the Statscraft window open, use `-s gui` instead of `-s work`, so I see every result.
  Each run that works is added to the syntax window Agent there; with `-s work` it goes to
  `.statscraft/sessions/work/syntax.sps`. Tell me where ("trail" in the JSON).
- Do not write data files unless I ask; nothing is saved to disk without a SAVE command.
- Report numbers from the "tables" in the JSON; do not compute them yourself.

实时会话的安全性

窗口只接受同一台计算机上同一用户的程序发送的语法:

  • 它只在 127.0.0.1 的一个随机 TCP 端口上监听,因此其他计算机无法访问它。
  • 启动时,它会生成一个随机令牌,并把地址和令牌写入 statscraft/gui.json,该文件在 Linux 上位于 $XDG_RUNTIME_DIR,在 Windows 上位于 %LOCALAPPDATA%,其他系统上位于 ~/.config。该文件只有该用户可以读取。
  • 每个请求都必须携带该令牌;不带令牌的请求会被拒绝。命令行从该文件读取令牌,并只将其发送到回环地址。
  • 大于 64 MB 的请求会被拒绝。
  • 窗口关闭时会删除它的文件。如果打开了两个窗口,后打开的窗口持有该文件,命令行和 MCP 会与它通信;它关闭后,如果先打开的窗口仍然开着,文件会回到那个窗口。

这在实际中意味着:任何以您的身份运行的程序都可以驱动窗口,正如它也可以直接运行 statscraft 一样。发送到窗口的语法可以做语法能做的一切:读取文件,以及用 SAVE 或 AGGREGATE OUTFILE 写入文件。同一连接还允许程序读取和更改您语法窗口中的文本、在新窗口中打开 .sps 文件,以及将语法窗口保存到文件;除非请求明确要求,保存不会覆盖另一个已存在的文件。请像对待能在您的 shell 中运行命令的智能体一样,对待能使用 -s gui 的智能体。

Syntax can also read a dataset from an OpenStatSpec database with GET DATA /TYPE=OPENSTATSPEC, a server included. An agent can then read any dataset the database account can read. The password never appears in the syntax, so it never lands in the Agent syntax window or a trail: a URL with one is refused, and Statscraft takes it from the STATSCRAFT_DB_PASSWORD environment variable of the window or the server. Give the agent an account that may only read when reading is all it needs.

Statscraft 0.61.0, release v0.61.0

连接您的 AI 智能体

Statscraft 内置了 MCP 服务器:statscraft mcp。支持 MCP 的 AI 智能体可以借此查看您的数据、查阅语法,并通过 Statscraft 运行语法,无需 shell。您的数据始终留在您的计算机上。

从窗口连接:Edit > Settings > AI agents

最简单的方法无需终端。在 Statscraft 窗口中打开 Edit > Settings…,然后选择 AI agents。这里列出所有受支持的智能体应用及其状态:未安装、未连接、已连接,或已连接到另一份 Statscraft(例如另一个文件夹中的旧安装)。

  • Claude Desktop:Install extension 从发布版本中下载适合您系统的本版本 Statscraft 扩展(.mcpb),用该版本的 SHA256SUMS 进行校验,保存到您的“下载”文件夹并打开它。Claude Desktop 随后显示该扩展;点击 Install。这是最持久的方式:扩展不依赖 Claude Desktop 的设置文件,而某些版本的 Claude Desktop 在启动或更新时会重写或清空该文件。如果没有任何东西打开,请把保存的文件拖到 Claude Desktop 的 Settings、Extensions 上。Connect via config file 则改为把条目写入设置文件,与 statscraft connect 的做法相同。
  • Connect 把 Statscraft 添加到其他某个应用中,Remove 将其再次移除,Connect all 连接所有尚未添加 Statscraft 的已安装应用,Claude Desktop 除外。
  • Check 重新读取应用的设置文件,显示每个路径,以及 Statscraft 条目此刻是否在其中。请在重启应用后使用它,查看应用是否保留了该条目。
  • 每次更改后,该部分会说明写入了哪些文件以及需要重启什么,例如完全退出 Claude Desktop 后再重新打开。如果更改时 Claude Desktop 正在运行,该部分也会提示:请完全退出 Claude Desktop 并重新连接,因为正在运行的 Claude Desktop 可能会把不含该条目的设置文件写回去。
  • 该条目启动随窗口一起提供的 statscraft 命令行程序,位于同一文件夹中(在 macOS 上,是包含 Statscraft.app 的文件夹)。如果该程序不在那里,该部分会提示,此时只有 Install extension 可用。

除扩展外,该部分所做的更改与 statscraft connect 完全相同,详见下文。

从终端连接:statscraft connect

一条命令即可把服务器添加到您计算机上安装的所有智能体:

statscraft connect

它会列出找到的智能体,逐一连接,并说明需要重启什么。可以随时再次运行:已连接的智能体保持不变。如果在设置文件更改时 Claude Desktop 正在运行,connect 会发出警告:请完全退出 Claude Desktop,然后再次运行该命令。

Claude Desktop 和 Claude Code 也有无需终端的方式:MCP 包和插件。要教智能体如何使用 Statscraft,请添加技能。

命令

命令功能 {#what-it-does}
statscraft connect连接找到的所有智能体
statscraft connect AGENT连接一个智能体
statscraft connect --list显示哪些智能体已安装、已连接,不做任何更改
statscraft connect --remove从所有包含 Statscraft 的智能体中移除它
statscraft connect --remove AGENT从一个智能体中移除它

在任一命令后加上 --json,即可得到智能体能读取的输出。当某个智能体无法连接时,退出代码为 1。

智能体为 claude-desktop、claude-code、codex(也可写作 chatgpt,指 ChatGPT 应用的 Codex 视图)、cursor、copilot(也可写作 vscode)、gemini 和 antigravity。在 Windows 上,WSL 中的智能体有 codex-wsl:Ubuntu 这样的 id;--list 会显示它们(参见 WSL 中的智能体)。

它会更改什么

每个智能体都会得到一个名为 statscraft 的条目。该条目通过完整路径启动您运行 connect 时所用的 Statscraft 程序,参数为 mcp。不经过 shell,也不依赖 PATH。如果您把 Statscraft 移动或重新安装到另一个文件夹,请再次运行 statscraft connect。

智能体更改内容
Claude Desktopclaude_desktop_config.json 中的 mcpServers.statscraft:在 Windows 上位于 %APPDATA%\Claude\,应用商店版本位于 %LOCALAPPDATA%\Packages\Claude_...\LocalCache\Roaming\Claude\;在 macOS 上位于 ~/Library/Application Support/Claude/;在 Linux 上位于 ~/.config/Claude/
Claude Code运行 claude mcp add --scope user statscraft -- PATH mcp,由 Claude Code 自己保存该条目
Codex,以及 ChatGPT 应用的 Codex 视图~/.codex/config.toml(或 CODEX_HOME 下)中的表 [mcp_servers.statscraft]
Cursor~/.cursor/mcp.json 中的 mcpServers.statscraft
VS Code(配合 Copilot)~/.copilot/mcp-config.json(或 COPILOT_HOME 下)中的 mcpServers.statscraft
Gemini CLI~/.gemini/settings.json 中的 mcpServers.statscraft
Antigravity~/.gemini/config/mcp_config.json 中的 mcpServers.statscraft

在 Windows 上,~ 是您的用户文件夹,例如 C:\Users\anna。

文件的处理方式:

  • 只更改 statscraft 条目。其他所有设置和其他所有服务器都保持不变,顺序、缩进和换行符也都不变。config.toml 中的注释同样保留。
  • 首次更改某个文件之前,会在它旁边保存一份副本,名为 FILE.statscraft-backup。之后的更改保留这第一份副本。
  • 文件先写入一个临时文件,然后再放到原位,因此智能体绝不会读到只写了一半的文件。
  • 不是纯 JSON 的文件(例如带注释的文件)不会被改动。您会收到一条指明该文件的消息,并可以按下文所示手动添加条目。
  • 当智能体的设置文件夹存在时(对 Claude Code 而言:当 claude 命令在 PATH 上时),即视为该智能体已安装。缺失的设置文件只会为已安装的智能体创建。

WSL 中的智能体

在 Windows 上,很多人在 WSL(Windows Subsystem for Linux,适用于 Linux 的 Windows 子系统)中运行 AI 智能体:例如安装在 Ubuntu 中的 Claude Code、Codex 或 Gemini CLI,或者把 Codex 设置为在 WSL 中运行的 ChatGPT 应用。这样的智能体从 Linux 主文件夹读取设置,而不是从 C:\Users\NAME 读取。安装在 Windows 上的 Statscraft 也能连接这些智能体,使它们使用 Windows 程序,并能看到打开的 Statscraft 窗口。

窗口和 statscraft connect 会询问 WSL 有哪些发行版(Docker Desktop 自带的发行版除外),并在每个发行版的主文件夹中查找。在那里找到的每个智能体都有自己的一行,以发行版命名,例如 Codex (WSL: Ubuntu),在命令行中的 id 为 codex-wsl:Ubuntu。只有在那里安装了的智能体才会出现对应的行。WSL 首次启动可能需要几秒钟;等待期间窗口会给出提示,若某个发行版 30 秒内没有响应,就放弃该发行版。

WSL 中的智能体更改内容
Codex,以及 WSL 模式下 ChatGPT 应用的 CodexLinux 主文件夹中 ~/.codex/config.toml 里的 [mcp_servers.statscraft](在 Linux 中设置的 CODEX_HOME 在 Windows 上看不到)
Gemini CLI~/.gemini/settings.json 中的 mcpServers.statscraft
Antigravity~/.gemini/config/mcp_config.json 中的 mcpServers.statscraft,前提是该文件夹存在
Claude Code在发行版内的登录 shell 中运行 claude mcp add --scope user statscraft -e ... -- PATH mcp,前提是在那里能找到 claude

条目包含的内容:

  • 命令是 Linux 所看到的 Windows 程序,例如 /mnt/c/Users/anna/AppData/Local/Programs/Statscraft/statscraft.exe。WSL 可以从 Linux 启动 Windows 程序,因此智能体与 Windows 上的 Statscraft 通信,而后者了解打开的窗口。
  • env 把 STATSCRAFT_WSL_DISTRO 设为发行版的名称,并设置 WSLENV=STATSCRAFT_WSL_DISTRO。WSLENV 让 WSL 把该变量传给 Windows 程序,Windows 程序由此得知智能体给出的是 Linux 路径。
  • Windows 通过 \\wsl$\DISTRO\home\NAME 访问这些文件。它们的合并、备份和写入方式与 Windows 上相同,新建的文件使用 Linux 换行符。

手动为 WSL 中的 Codex 添加:

[mcp_servers.statscraft]
command = "/mnt/c/Users/anna/AppData/Local/Programs/Statscraft/statscraft.exe"
args = ["mcp"]
env = { STATSCRAFT_WSL_DISTRO = "Ubuntu", WSLENV = "STATSCRAFT_WSL_DISTRO" }

为 WSL 中的 Claude Code 添加,在其终端中运行:

claude mcp add --scope user statscraft -e STATSCRAFT_WSL_DISTRO=Ubuntu -e WSLENV=STATSCRAFT_WSL_DISTRO -- /mnt/c/Users/anna/AppData/Local/Programs/Statscraft/statscraft.exe mcp

然后按下文所述重启智能体:在 WSL 中启动新的 Claude Code 或 Gemini CLI 会话,或者退出 ChatGPT 应用后重新打开。

路径:智能体使用 Linux 路径,服务器使用 Windows 路径。

  • 在工具参数中(file、folder、xlsx,以及 open_syntax_file 和 save_syntax 的路径),可以使用 Linux 路径:/mnt/c/data/survey.sav 会变成 C:\data\survey.sav,Linux 内部的路径(例如 /home/anna/survey.sav)会变成 \\wsl$\Ubuntu\home\anna\survey.sav。
  • 语法中的文件名(GET FILE、SAVE 等)不会被转换。请把它们写成 Windows 路径:GET FILE='C:\data\survey.sav'. window_status 会给出 platform 和 wsl_distro,供智能体判断。
  • 运行保存其语法的位置(trail)和它写出的工作簿以两种形式返回:trail_wsl 和 xlsx_wsl 中是 Linux 路径。

如果 claude 已安装但在 WSL 中找不到,很可能是它的文件夹只在 ~/.bashrc 中加入了 PATH;请按上文手动添加条目。

重启智能体

智能体在启动时读取设置。连接之后:

智能体操作
Claude Desktop完全退出(也要从系统托盘或菜单栏退出),然后重新打开;仅关闭窗口是不够的
Claude Code启动新会话
Codex,ChatGPT 应用退出后重新打开
Cursor, VS Code, Antigravity退出后重新打开
Gemini CLI启动新会话

然后问智能体 Statscraft 为它提供了哪些工具,或者让它描述一个数据文件。

如果智能体看不到 Statscraft

  • Claude Desktop 只在启动时读取设置。在 Windows 上,请确认退出后没有残留的 Claude 进程(在 PowerShell 中运行 Get-Process claude 没有任何输出),然后重新打开。Statscraft 列在 Settings > Desktop app > Extensions 下的 Local MCP servers 中;您安装的 MCP 包显示在它上方的 Extensions 下。Claude Desktop 会把每个服务器的启动记录在 mcp-server-statscraft.log 中:在 Windows 上位于 %LOCALAPPDATA%\Claude\logs,在 macOS 上位于 ~/Library/Logs/Claude。
  • ChatGPT 应用只在其 Codex 视图中使用本地工具,在普通对话中不使用。请完全退出该应用,重新打开,然后在 Codex 视图中提问。
  • 要查看服务器本身能否启动,请在终端中运行 statscraft mcp:它会在输入端等待智能体的消息;按 Ctrl+C 结束。

在 ChatGPT 应用中,这些工具只在 Codex 视图中可用。普通 ChatGPT 对话无法使用在您计算机上运行的工具,即使应用的设置中列出了 Statscraft 服务器。

撤销

在窗口中点击 Remove,或运行 statscraft connect --remove,都会再次移除 statscraft 条目,其他一切保持原样。若要让文件恢复到首次更改之前的原样,请把 .statscraft-backup 副本放回原位。这样一来,您在此期间更改的设置也会丢失。

Claude Desktop:双击 MCP 包

每个发布版本都在 Releases 页面上为每个系统提供一个 MCP 包:

  • statscraft-X-windows-x86_64.mcpb 适用于 Windows
  • statscraft-X-macos-universal.mcpb 适用于 macOS,包括 Apple 芯片和 Intel
  • statscraft-X-linux-x86_64.mcpb 适用于 Linux

在窗口中,Edit > Settings > AI agents 下的 Install extension 会替您完成这一步。手动方式:下载适合您系统的包并双击它,或者把它拖到 Claude Desktop 的 Settings、Extensions 上。Claude Desktop 会显示 Statscraft 提供的工具,并请您安装。就这么简单:无需终端,也无需设置文件。

MCP 包自带一份 statscraft 程序,因此即使在没有安装 Statscraft 的地方也能工作。这份程序不会随 statscraft update 更新;请改为安装新版本的 MCP 包。如果您有窗口,窗口仍会显示智能体运行的一切。

已知限制:macOS 程序未签名,因此 macOS 可能会阻止它;如果 Claude Desktop 提示扩展无法启动,请改用 statscraft connect。Linux 版 Claude Desktop 仍是测试版。

Claude Code:插件

在 Claude Code 中输入:

/plugin marketplace add statscrafthq/statscraft
/plugin install statscraft@statscraft

然后启动新会话。该插件会添加 MCP 服务器和技能。它以 statscraft mcp 启动服务器,因此 statscraft 必须在您的 PATH 上。Windows 安装程序、.deb 软件包和 Linux tar 压缩包会把它加入 PATH;Windows 便携版 .zip 和 macOS 下载版不会,需要您按安装与更新中的说明自行添加。请在新终端中运行 statscraft --version 检查。如果不在 PATH 上,请用程序的完整路径运行 statscraft connect claude-code:插件中的技能在该条目下仍然有效。

如果 Claude Code 之前已用 statscraft connect 连接过,现在它就有两个服务器条目。statscraft connect --remove claude-code 会移除较早的那个条目。

教会您的智能体:技能

技能 statscraft-analysis 告诉智能体如何使用 Statscraft:先查看数据,查阅每条命令,先检查,分小步运行,阅读每条回复,报告结果表格中的数字而绝不自行计算,除非被要求否则不写任何文件。它采用 Agent Skills 格式,因此许多智能体应用都能读取。它是一个文件夹,内含一个 SKILL.md,位于代码仓库的 plugins/statscraft/skills/statscraft-analysis 中。

  • Claude Code:随插件一起提供。
  • Claude Desktop 和 claude.ai:从 Releases 页面下载 statscraft-X-skill.zip,并在设置中将其作为技能上传。
  • Codex 和 ChatGPT 应用的 Codex 视图:对 Codex 说 $skill-installer install https://github.com/statscrafthq/statscraft/tree/main/plugins/statscraft/skills/statscraft-analysis,然后重启它。
  • 其他读取 Agent Skills 的智能体:把该 zip 解压到它们的技能文件夹中,使其中包含 statscraft-analysis/SKILL.md。

有 MCP 工具时,该技能使用 MCP 工具;智能体只有 shell 时,则使用 statscraft 命令行。

手动连接

想自己编辑文件?请使用您的 statscraft 程序的完整路径。statscraft connect --list --json 会在 server 下打印该路径;在 Windows 上运行 where statscraft,在其他系统上运行 which statscraft,也能显示它。Windows 安装程序把它放在 C:\Users\NAME\AppData\Local\Programs\Statscraft\statscraft.exe。下面的示例使用 /usr/bin/statscraft。在 JSON 中,Windows 路径的每个反斜杠都要写两次:"C:\\Users\\anna\\AppData\\Local\\Programs\\Statscraft\\statscraft.exe"。

Claude Code,在终端中运行一行命令:

claude mcp add --scope user statscraft -- /usr/bin/statscraft mcp

Claude Desktop(claude_desktop_config.json)、Gemini CLI(~/.gemini/settings.json)和 Antigravity(~/.gemini/config/mcp_config.json):在 mcpServers 下添加条目,与已有的服务器并列。

{
  "mcpServers": {
    "statscraft": {
      "command": "/usr/bin/statscraft",
      "args": ["mcp"]
    }
  }
}

Cursor(~/.cursor/mcp.json):

{
  "mcpServers": {
    "statscraft": {
      "type": "stdio",
      "command": "/usr/bin/statscraft",
      "args": ["mcp"]
    }
  }
}

VS Code(配合 Copilot)(~/.copilot/mcp-config.json):

{
  "mcpServers": {
    "statscraft": {
      "type": "stdio",
      "command": "/usr/bin/statscraft",
      "args": ["mcp"],
      "tools": ["*"]
    }
  }
}

Codex 和 ChatGPT 应用的 Codex 视图(~/.codex/config.toml):

[mcp_servers.statscraft]
command = "/usr/bin/statscraft"
args = ["mcp"]

浏览器中的 ChatGPT 和 ChatGPT 应用中的普通对话无法在您的计算机上启动程序,因此不能以这种方式使用 Statscraft。

面向智能体

有 shell 的智能体可以自行连接。先运行 statscraft connect --list --json,再针对您自己这个智能体运行 statscraft connect AGENT --json,并把回复中 restart 字段的内容告诉用户。面向 AI 智能体的 Statscraft 介绍了连接后如何工作。

Statscraft 0.61.0, release v0.61.0

MCP 服务器

statscraft mcp 让 AI 智能体通过工具而不是 shell 命令来使用 Statscraft。它通过标准输入和输出使用 Model Context Protocol(MCP,模型上下文协议),因此任何能运行本地 MCP 服务器的智能体应用都可以使用它:Claude Desktop、Claude Code、Codex(包括 ChatGPT 应用中的 Codex)、Cursor、VS Code(配合 Copilot)等。它随 statscraft 命令行一起提供,无需另外安装,数据也从不离开您的计算机。

连接智能体最简单的方法是 statscraft connect,它会找到您已安装的智能体应用,并把 Statscraft 添加到每个应用中。Claude Desktop 也可以双击 MCP 包来安装,Claude Code 则可以通过插件安装;参见连接您的 AI 智能体。如需手动设置,请给智能体提供命令 statscraft mcp;如果 statscraft 不在您的 PATH 上,请写出它的完整路径。

工具

工具输入返回内容
describefile(.sav 或 .zsav 文件),或 session字典和计数,对会话还会返回它保存的内容;与 statscraft describe --json 的 JSON 相同
list_commands无每条受支持的命令及其一行摘要,与 statscraft help 相同
command_helpcommand一条命令的语法、规则和示例,与 statscraft help COMMAND 相同
check_syntaxsyntax 或 file,以及可选的 lines、session、folder、vega_lite、encoding检查结果,与 statscraft check --json 相同;不保存也不写入任何内容
run_syntax与 check_syntax 相同,另加可选的 xlsx、xlsx_one_sheet、xlsx_no_titles、plugins、plugin_templates、charts 和 chart_format;或用 window(可选 lines)代替 syntax 和 file运行结果,与 statscraft run --json 相同;会话保存新的状态,trail 说明其语法保存在何处
describe_pluginprogram(插件的绝对路径)插件的名称、版本和设置,每项设置附带其类型、默认值以及保存它的数据文件属性
check_plugin_updateprogram(插件的绝对路径)插件是否提供更新的版本,与 statscraft update --check --plugin 相同:plugin、current、latest、update、notes;不安装任何东西
window_status无Statscraft 窗口是否已打开,若已打开,则给出其数据集和输出文档;还有 platform(windows、macos、linux),智能体在 WSL 中运行时另有 wsl_distro
list_syntax_windows无打开的窗口中的语法窗口:id、name、file、unsaved、lines,以及它是否为 Agent 窗口、指定窗口或用户最近使用的窗口
read_syntaxwindow语法窗口的文本,每行附带行号
edit_syntaxwindow、mode、text,以及 lines 或 before更改文本:replace 替换 lines 指定的行(文本为空则删除这些行),insert 插入到第 before 行之前,append 追加,或 replace_all 全部替换;返回新文本所占的行
new_syntax_window可选的 name 和 text一个新的语法窗口,为空或包含给定文本
open_syntax_filepath在语法窗口中打开的 .sps 文件,或已打开该文件的窗口
save_syntaxwindow,可选的 path 和 overwrite把窗口写入它自己的文件或 path
close_syntaxwindow,可选的 discard关闭语法窗口,与在该窗口中选择 File > Close 相同
export_outputpath,可选的 folder、format、one_sheet、selected、hidden把打开的窗口的输出写入 Excel 工作簿、网页或 PDF,与窗口的 File > Export 和 statscraft export 相同
read_output可选的 document打开的窗口中某个输出窗口的内容,与 statscraft output --json 相同:每个标题、表格和图表,以及它是否隐藏或选中,还有该窗口显示哪些类型
undo无撤销打开的窗口中最近一次更改数据的运行,与窗口的 Edit > Undo 和 statscraft undo 相同;在 undone 下给出那次运行的语法;每次调用再往前撤销一步
redo无在打开的窗口中重做最近一次撤销的运行,与窗口的 Edit > Redo 和 statscraft redo 相同;在 redone 下给出那次运行的语法
add_chartchart,可选的 session 和 vega_lite检查图表并把它添加到指定输出文档,返回内容与一次运行的结果相同;文本以 chart added to output document NAME 开头
run_codecode, a JavaScript async arrow functionwhat the function returned, as JSON under value, with ok, logs and error; see Code mode
apply_plansyntax, database (sqlite, postgres, mysql or dolt), location, dataset, optional apply, actor (required to apply), expected_branch, expected_head, profilethe JSON of statscraft plan with a database and --name: the plan, plan_hash and source_hash, and after an apply applied; see Editing a dataset in a database
  • syntax 是一条或多条命令的文本;file 是 .sps 文件的绝对路径。两者给出其一。
  • lines 把运行限制在某个行范围内的命令,例如 "12-20"。行号仍按整段文本计算。
  • folder 是语法中相对文件名的起始绝对文件夹。默认:您的主文件夹。为保险起见,请在语法中使用绝对路径。
  • xlsx、xlsx_one_sheet、xlsx_no_titles、plugins、plugin_templates、vega_lite、encoding、charts 和 chart_format 的作用与命令行中同名的 run 选项相同。路径请写成绝对路径;相对的 charts 文件夹从 folder 开始。导出全部输出介绍工作簿,使用插件的表格介绍插件。
  • 在 WSL 中运行、使用 Windows 上 Statscraft 的智能体,可以在参数中给出 Linux 路径;服务器会转换它们。在语法内部,文件名必须是 Windows 路径。参见 WSL 中的智能体。
  • window 用 id 或名称指定打开的窗口中的一个语法窗口,与 list_syntax_windows 显示的相同。语法窗口工具只在窗口打开时可用;窗口未打开时,它们会失败并提示 “no Statscraft window is running”。

一次运行或检查会以结构化内容返回命令行中介绍的 JSON,并以 Markdown 文本返回表格和图表,附带一行摘要,供只显示文本的应用使用。语法错误或运行错误是正常结果:ok 为 false,errors 给出行、列和预期的内容,智能体可以据此修正语法并重试。服务器完全无法执行的调用,例如文件缺失或参数错误,会被标记为工具错误。

服务器在连接时还会把工作流程发送给智能体,并以提示词 analysis 的形式提供:先描述数据,查阅每条命令,先检查,分小步运行,阅读 ok、errors 和警告,并报告结果表格中的数字,而不是自行计算。

每一步都留下语法

智能体通过 run_syntax 所做的一切都保留为可读的语法,用户可以检查、修改,并在没有智能体的情况下再次运行:

  • 在打开的窗口中,每次成功的运行都会添加到名为 Agent 的语法窗口中。该窗口在第一次运行时打开;如果用户关闭了它,下一次运行会打开一个新的。每次运行都位于一行带时间的注释之下,例如 * Agent 14:32.,后面是实际运行的语法,一字不差。用户可以像在任何语法窗口中一样编辑它,用 Ctrl+Enter 运行其中的行,并保存它。从命令行用 statscraft run -s gui 发送的运行也会进入这里。
  • 从语法窗口发起的运行(带 window 的 run_syntax)不会被复制:该窗口的文本本身就是它的记录。
  • 在文件会话中,每次成功的运行都会添加到会话文件夹中的 syntax.sps,位于一行带日期和时间的注释之下。
  • 失败的运行(ok 为 false)没有更改任何东西,也不留下任何东西;检查同样如此。
  • 结果中的 trail 以及文本中的 syntax kept in: 一行说明语法保存到了哪里:syntax window Agent,或文件的路径。

您自己的图表

过程会绘制自己的图表。当用户想要一张没有任何过程能生成的图表时,例如把两次运行得到的去年数字和今年数字并排展示,add_chart 会把它放进输出,并按 Statscraft 的方式绘制:

  • chart 可以是 run_syntax 在 charts 下返回的图表 JSON(智能体因此可以拿来某个过程的图表,修改其标题、标签、类型或数字),也可以是一个简单的 Vega-Lite 规范:一个视图,行内联在 data.values 中,标记为 bar、line、area、point 或 arc。两者都在作为输入的图表中介绍。
  • 数值按原样绘制:不做任何计数、求和或分组。数字应当来自结果表格。
  • 在打开的窗口中,图表进入指定输出窗口,用户可以在那里查看、复制它,在 Excel、Word 或 PowerPoint 中打开它,并与其他输出一起保存或导出。结果中的 commands[0].document 给出该文档的名称。
  • 该工具运行语法 BEGIN CHART(Statscraft 的一项扩展),其中包含图表的 JSON。这段语法像任何运行一样被保存:在 Agent 语法窗口中,或在文件会话的 syntax.sps 中,因此再次运行它会再次显示该图表。
  • 文件会话在调用之间把输出保存在其文件夹中。先添加图表,准备好后再通过 run_syntax 用 OUTPUT EXPORT 或 OUTPUT SAVE 写出文档。
  • 无法绘制的图表、拼错的字段,或 Statscraft 不读取的 Vega-Lite 功能,都是需要修正的错误,与语法错误一样:ok 为 false,消息会指出问题所在。此时不会添加任何内容。

Code mode

run_code takes code, a JavaScript async arrow function, and runs it in a sandbox inside the server. There every other tool is a function of the object statscraft, with the tool’s name and its arguments as one object, and returns what the tool returns: statscraft.describe({ file }), statscraft.run_syntax({ session, syntax }), statscraft.read_output({}) and so on. An agent uses it when one step depends on the result of another, or when a run gives far more than the agent needs: the script runs the syntax, keeps the numbers it wants and returns only those, all in one call.

  • Each function returns the tool’s structured result, the same JSON the tool gives, or its text for list_commands and command_help. A run with ok false comes back as it is; a tool error (a bad argument, a missing file) is thrown as an Error with the tool’s message, which the script can catch.
  • A table in run_syntax’s result has title, columns (names, the first row_headers of them for the row labels) and rows, each an array in the order of columns: text for a label, a raw number, null for an empty cell. The chi-square table of a CROSSTABS, for one, has the columns ["Statistic", "Value", "df", "Asymptotic Sig. (2-tailed)"] and a first row like ["Pearson Chi-Square", 39.48, 16, 0.00093], so rows[0][3] is the Pearson significance.
  • The reply has ok, value (what the function returned, as JSON), logs (the lines console.log wrote) and error (its message, and line and column in code where they are known). When the script throws or reaches a limit, ok is false.
  • Data still change only through syntax: every run_syntax the script makes is kept in the trail as a direct call is (Every step leaves syntax). The script itself is not kept.
  • The sandbox has no files, network, modules, timers, environment or processes. The script reaches only the statscraft object, so it can do what the tools can do and nothing more. run_code is not in the object: a script cannot start another script.
  • Limits, each ending the script with an error that names it: 60 seconds of the script’s own time (time inside tool calls does not count, so a long analysis is not cut short), 512 MB of memory and a 1 MB stack.
  • statscraft code runs the same scripts from the command line.

An example. A staff survey has questions q1 to q12 and a department variable dept. Which questions did more than 5% of the staff skip, and does skipping depend on the department?

async () => {
  const session = 'staff';
  statscraft.run_syntax({ session, syntax: "GET FILE='/home/anna/data/staff_survey.sav'.\n" });
  const data = statscraft.describe({ session });
  const skipped = data.variables
    .filter(v => /^q\d+$/.test(v.name))
    .filter(v => 1 - v.n_valid / data.case_count > 0.05)
    .map(v => v.name);
  const sig = {};
  for (const name of skipped) {
    const syntax = `COMPUTE skip = MISSING(${name}).\nCROSSTABS /TABLES=skip BY dept /STATISTICS=CHISQ.\n`;
    const run = statscraft.run_syntax({ session, syntax });
    if (!run.ok) return run.errors;
    const table = run.commands[1].tables.find(t => t.title.startsWith('Chi-Square Tests'));
    sig[name] = table.rows[0][3];
  }
  return { skipped, pearson_sig: sig };
}

The reply carries a few names and numbers instead of every table, and the session’s trail holds each COMPUTE and CROSSTABS the script ran.

使用插件的表格

插件会美化一次运行在工作簿中生成的 CTABLES 表格:颜色、注释、列宽以及其他外观。智能体通过 describe_plugin 获取插件的设置。每项设置保存在一个数据文件属性中,例如 plugin_acme_tables_confidence,运行时从活动数据的该属性中读取每项设置,没有时使用插件的默认值。要更改某项设置,智能体在表格之前运行 DATAFILE ATTRIBUTE ATTRIBUTE=plugin_acme_tables_confidence('90').(是/否写作 Yes 或 No,颜色写作 #rrggbb,样式写成 JSON);SAVE 会把它与数据一起保存。然后:

{ "file": "/home/anna/jobs/tables.sps", "session": "work", "xlsx": "/home/anna/jobs/tables.xlsx",
  "xlsx_one_sheet": true, "plugins": ["/home/anna/plugins/acme-tables"] }

插件失败则运行失败,并给出插件的消息。在打开的窗口中,plugins 的作用相同:设置取自运行之后窗口活动数据的属性,并且只有本次运行的工作簿使用插件的外观。窗口自身的输出仍使用 Edit > Settings > Plugins 中的插件,export_output 写出的就是这些。

语法窗口

窗口打开时,智能体可以像用户一样在用户的语法窗口中工作:

  • list_syntax_windows 和 read_syntax 显示其中的内容,包括未保存的更改。行号与运行时计算的行号一致。
  • edit_syntax 更改编辑器中的文本;用户会立即看到更改,并可以在该编辑器中用 Ctrl+Z 撤销。它从不运行任何东西,也不写入任何文件。
  • 带 window 的 run_syntax 运行该窗口的文本,带 lines 时运行这些行涉及的命令,与在该窗口中使用 Run 和 Ctrl+Enter 完全相同:相对文件名从该窗口的文件开始,错误会标记在其页边。
  • new_syntax_window 和 open_syntax_file 会打开一个窗口;智能体打开的窗口会接收从对话框粘贴的语法,与用户打开的窗口一样。Agent 窗口从不接收。
  • save_syntax 把窗口写入它自己的文件,或写入 path。除非 overwrite 为 true,否则它不会替换任何其他已有文件,并且绝不替换另一个语法窗口所持有的文件。
  • close_syntax 关闭窗口。有未保存更改的窗口会保持打开,除非 discard 为 true;程序的最后一个窗口总是保留,因为关闭它会退出 Statscraft。

当用户要求修正或解释其语法时,智能体会读取窗口,说明它打算更改什么,用 edit_syntax 进行更改,然后从窗口中运行。

export_output 像 File > Export 一样把指定输出窗口写入 path:format 为 xlsx、html 或 pdf(默认:根据扩展名),one_sheet 用于 Excel,selected 只导出选中的表格,hidden 同时导出隐藏的项目。相对的 path 从 folder 开始。它会替换已有文件。

undo 撤销打开的窗口中最近一次更改数据的运行,与窗口中的 Edit > Undo 相同;输出保留。每次调用再往前撤销一步,最多 10 步。redo 重做最近一次撤销的运行,与 Edit > Redo 相同;撤销后若又更改了数据,就不能再重做。没有可撤销或可重做的内容时,两者都会失败。文件会话不支持这两项。

read_output 让智能体看到用户在输出窗口中看到的内容:指定输出窗口,或输出文档 document。其结构化内容是 statscraft output --json 的 JSON;其文本是一行摘要加上表格,与 run_syntax 给出的形式相同,隐藏或选中的表格都有相应标记。

Editing a dataset in a database

apply_plan edits a dataset stored in an OpenStatSpec database in place, as statscraft plan --apply does: the same dataset and the same table, with no copy.

  • syntax takes only the bounded subset of plan: RECODE, VARIABLE LABELS, VALUE LABELS, ADD VALUE LABELS, FORMATS, VARIABLE LEVEL, simple COMPUTE and IF, and EXECUTE. profile picks 0.1, 0.2 or 0.3 (the default).
  • location is the absolute path of a SQLite file, or the URL of a PostgreSQL, MySQL or Dolt database. A URL with a password is refused; the server takes the password from STATSCRAFT_DB_PASSWORD in its own environment.
  • Without apply, or with apply false, the tool only previews: it reads the dataset’s dictionary, lowers the syntax to a plan and writes nothing. With apply true it applies the plan in one transaction with one audit row naming actor, which an apply requires so that every audit row names who made the change.
  • On Dolt, an apply needs expected_branch and expected_head: the database must be on that branch at that commit, with a clean working set. The tool never commits, branches or resets; the reply has "committed": false and the commit is yours. Put all edits of one step into one plan.
  • Errors carry a stable code under error. A call the tool refuses before connecting, such as an apply without actor or a URL with a password, has the code usage. When the syntax is at fault they also carry line and column, and come as a normal result for the agent to fix; others, such as an unknown dataset or a database that cannot be reached, are tool errors.

Preview first, then apply. After an apply, read the dataset back from the database, for example with GET DATA /TYPE=OPENSTATSPEC in run_syntax, instead of assuming what the edit did.

会话与窗口

会话在调用之间保存数据、设置、宏和命名数据集,与 statscraft run -s NAME 相同(参见会话)。

  • 当 Statscraft 窗口打开时,不带 session 的调用会发送到窗口(会话 gui)。您会看到每个表格出现在指定输出窗口中,每条命令出现在日志中,并且可以在智能体的各步之间继续在窗口中工作。
  • 当没有打开的窗口时,不带 session 的调用使用名为 work 的会话。
  • MCP 服务器的文件会话位于您的用户数据文件夹中,而不是智能体应用启动服务器时所在的文件夹:在 Linux 上是 ~/.local/share/statscraft/sessions(或 $XDG_DATA_HOME/statscraft/sessions),在 macOS 上是 ~/Library/Application Support/Statscraft/sessions,在 Windows 上是 %LOCALAPPDATA%\Statscraft\sessions。删除某个会话的文件夹即可重新开始,也可以让智能体使用一个新的会话名称。

安全性

  • The server can do what the command line can do, and nothing more. Syntax can read files, and it can write them with SAVE, AGGREGATE OUTFILE, OUTPUT EXPORT or the xlsx argument. check_syntax writes nothing; nothing is written without one of those, apart from the read that GET DATA records in an OpenStatSpec database and the edits apply_plan applies there (below).
  • The tools tell the agent app which of them only read (describe, list_commands, command_help, check_syntax, window_status, list_syntax_windows, read_syntax, read_output), which change only the window’s syntax windows (edit_syntax, new_syntax_window, open_syntax_file) or add to its output (add_chart, which writes no file), that close_syntax can lose unsaved syntax and undo and redo change the data, that run_syntax, save_syntax and export_output can change files, that apply_plan can change a dataset in a database, and that run_code can do whatever the other tools can. Agent apps ask you before a tool runs, unless you allowed it; allow run_syntax only for agents you trust with your files.
  • GET DATA /TYPE=OPENSTATSPEC reads a dataset from an OpenStatSpec database, which may be a server on the network. The syntax never holds the password: a URL with one is refused, and the server or the window takes it from STATSCRAFT_DB_PASSWORD in its own environment. The read is logged in the database’s catalog, except on Dolt and in check_syntax, which write nothing there. apply_plan reaches a database in the same way, with the password from the same variable.
  • 服务器只与启动它的应用通信,通过标准输入和输出进行。它不打开任何网络端口。对窗口的调用使用窗口的本地连接,详见 AI 智能体。

Statscraft 0.61.0, release v0.61.0

插件

插件为自定义表格的单元格着色并添加注释。例如,它可以把单元格按热力图着色,标记基数较小的单元格,为单元格添加备注,或让您导出的 Excel 文件拥有自己的外观。

插件是一个独立的程序。您只需在窗口中添加一次,之后每次生成自定义表格的运行结束后,Statscraft 都会运行它。

添加插件

  1. 选择 Edit > Settings > Plugins。
  2. 点击 Add plugin…,选择插件的程序文件。

每个插件占一行,显示其名称和版本、一个用于启用或停用的复选框、完整路径,以及 Up、Down、Remove 和 Settings… 按钮。如果某个插件无法使用,该行会说明原因。

下一次运行后,输出窗口会显示这些颜色。带有红色小角标的单元格有注释:将鼠标指向它即可阅读。当您更改插件、插件顺序或其设置时,所有表格都会重新装饰。

多个插件

插件按列表顺序运行,每个插件使用自己的设置。如果两个插件设置同一项样式,例如单元格的填充色,以后运行的为准。如果它们设置的是不同的样式,两者都会显示:例如一个插件的填充色和另一个插件的粗体文字。

运行失败或耗时超过两分钟的插件不会添加任何内容,状态栏会说明原因。其他插件仍然生效。

插件设置

Settings… 打开该插件针对当前数据的设置。有单独标题的设置会归在该标题下。

  • 点击 OK,设置会随数据一起保存。保存数据文件即可把设置带到另一台电脑。
  • 标有 (all data files) 的设置则保存在本机上,对所有数据文件使用您最后选择的值。没有打开数据时也可以设置它。在命令行中,请在语法里用 DATAFILE ATTRIBUTE 指定。
  • 留空的设置使用插件的默认值。
  • 样式设置会显示一个示例,无论窗口使用什么主题,都像 Excel 中一样白底黑字。Define… 用于设置字体、字号、粗体、斜体、文字颜色、填充色和对齐方式。
  • 有些设置带有预设:可以从列表中选择的已保存值。输入名称并点击 Save as new 即可添加一个预设。选择一个预设会填入它的值和名称;修改其中任一项后,点击 Save 将更改保存到该预设,或点击 Remove 删除它。预设属于窗口,因此对所有数据文件都可用。

设计模板

设计模板是某个插件的一组命名设置,例如每个客户一种外观。

  • 在 Plugin Settings 顶部的 Template 行中选择一个模板,或选择 (none)。
  • 输入名称并点击 Save as template,即可保存当前设置。Delete 删除所选模板。
  • OK 使所选模板生效。模板生效期间,其设置适用于所有数据文件。属于单个数据文件的设置仍来自数据,标有 (all data files) 的设置仍来自本机。
  • Export… 将所选模板和该插件的预设写入一个文本文件。Import… 读取这样的文件,例如同事导出的文件。

各处显示的内容

Statscraft 将颜色和注释与输出一起保存,因此已保存的输出文件(.scout)无需插件即可再次显示它们。

位置插件可以更改的内容
Excel 工作簿填充色、文字颜色、粗体、斜体、对齐方式、边框、字体和字号、列宽、行高,以及作为 Excel 批注的注释
网页和复制的表格相同的样式,注释显示为提示框;宽度和高度由浏览器决定
输出窗口填充色、文字颜色、粗体、斜体、边框和对齐方式;窗口保持自己的字体和布局

插件是否写入注释,由插件自身的设置决定。

更新

提供更新的插件在其所在行中有 Check now 按钮。Plugins 页面打开期间,Statscraft 还会每天检查一次每个这样的插件。有新版本时,该行会显示出来,并附有插件的说明和一个 Update 按钮。

在您点击 Update 之前,不会安装任何内容。之后 Statscraft 会下载新程序,用插件提供的校验和进行核对,替换旧程序,并重新装饰表格。任何一步失败,都会保留旧程序。

在共用的计算机上

插件列表属于您自己的 Statscraft 设置,因此在有多个用户账户的计算机上,每个用户都要自己添加需要的插件。Statscraft 从插件程序文件所在的文件夹运行插件,其他用户只有在能读取该文件时才能添加同一个文件:您的下载(Downloads)或文档(Documents)文件夹中的文件通常只有您自己能读取。要共享插件,请让管理员把插件程序放到所有用户都能读取、但只有管理员能修改的文件夹中,例如 Windows 上 C:\Program Files 下的某个文件夹。然后每个用户从那里添加它。Update 无法替换这种文件夹中的程序,因此旧版本会一直保留,直到管理员把新版本放到原来的位置。

不使用窗口运行插件

在命令行中,--plugin 让插件为工作簿中的自定义表格设置样式:

statscraft run job.sps --xlsx tables.xlsx --plugin /path/to/plugin
  • 设置来自当前数据文件,即窗口保存在其中的设置。要在语法中设置某项,请将其指定为名为 plugin_<name>_<key> 的数据文件属性(插件名称和设置的键,均为小写,其他字符写作 _),例如 DATAFILE ATTRIBUTE ATTRIBUTE=plugin_example_comments('No').
  • --plugin-template FILE 应用一个用 Export… 制作的模板文件,作用与窗口中生效的模板相同。
  • 要使用多个插件,请多次指定 --plugin。插件按指定的顺序运行。与窗口中不同,插件失败会停止运行。
  • statscraft update --check --plugin PROGRAM 询问插件是否有新版本。它从不安装任何内容。

AI 智能体通过 MCP 服务器使用同样的功能(见使用插件生成表格)。

编写您自己的插件

编写插件说明了插件读取和写入的 JSON,并附有一个用 Rust 编写的小型示例插件。

Statscraft 0.61.0, release v0.61.0

Commands

One page per supported command, generated from the same table that the parser and statscraft help use, so the pages always match the program.

Data files and dictionary

命令功能 {#what-it-does}
GETRead a data file and make it the active dataset.
GET DATARead a text data file, a sheet of a workbook or a dataset of an OpenStatSpec database as the active dataset.
GET TRANSLATERead a tab-delimited text file, a dBASE file or an old Excel workbook.
GET STATARead a Stata data file (.dta) and make it the active dataset.
IMPORTRead a portable (.por) file and make it the active dataset.
SYSFILE INFOShow the dictionary of a data file without opening it as the active dataset.
SAVEWrite the active dataset to a data file.
SAVE TRANSLATEWrite the active dataset to a CSV or tab-delimited text file, an Excel workbook, a Stata file, a SAS transport file or a dBASE file.
SAVE CODEPAGEWrite the active dataset to a data file whose text is in a code page.
EXPORTWrite the active dataset to a portable (.por) file.
XSAVEWrite the cases to a data file as the next data pass reads them.
NEW FILEStart a new, empty active dataset.
ADD CASEA Statscraft extension: one blank case after the last case of the active dataset.
ADD FILESAppend the cases of several data files, matching variables by name.
MATCH FILESCombine the variables of several data files case by case or by key.
STAR JOINAdd the fields of lookup files to every case of a data file, by keys, as an SQL left join.
UPDATEReplace values of a primary file with the values of transaction files, by key.
COMPARE DATASETSCompare the values and dictionary of the active dataset with another dataset or .sav file.
VARIABLE LABELSSet the labels of variables.
VALUE LABELSReplace the value labels of variables.
MISSING VALUESDeclare user-missing values.
VARIABLE LEVELSet the measurement level of variables.
VARIABLE WIDTHSet how many characters wide variables show in the data grid.
FORMATSSet the display format of variables.
PRINT FORMATSSet the print format of variables: how procedures and PRINT show them.
WRITE FORMATSSet the write format of variables: how WRITE writes them.
RENAME VARIABLESChange the names of variables.
DELETE VARIABLESRemove variables from the dataset.
SORT CASESSort the cases by the values of variables.
SORT VARIABLESPut the variables in order by a property of their dictionary entries.
SHIFT VALUESNew variables that hold the value of the same variable in an earlier or later case.
WEIGHTWeight the cases by a variable, or turn weighting off.
AGGREGATEAggregate groups of cases into new variables or a new dataset.
VARSTOCASESTurn groups of variables into cases: one new case per variable of the group.
CASESTOVARSTurn groups of cases into one case each, with a variable per value of an index.
FLIPTranspose the data: variables become cases and cases become variables.
ADD VALUE LABELSAdd or change value labels, keeping the other labels of the variables.
FILE LABELSet the label of the data file.
DOCUMENTAdd free text to the documents of the data file.
ADD DOCUMENTAdd quoted lines to the documents of the data file.
DROP DOCUMENTSRemove the documents of the data file.
VARIABLE ROLESet the role of variables for dialogs.
VARIABLE ALIGNMENTSet the alignment of variables in the data grid.
VARIABLE ATTRIBUTESet or delete custom attributes of variables.
DATAFILE ATTRIBUTESet or delete custom attributes of the data file.
ALTER TYPEChange the type, string width or format of variables.
APPLY DICTIONARYCopy dictionary information from a data file or dataset to the active dataset.
DATA LISTDefine text data, inline or in a file, and read it as the new active dataset.
KEYED DATA LISTRead variables from the record of a text file that a key variable picks, for each case.
BEGIN DATAInline data for the DATA LIST before it, up to a line that holds END DATA.
MATRIX DATARead matrix materials (correlations, means, counts) as a matrix data file.
MCONVERTMatrix data between covariances and correlations with standard deviations.
INPUT PROGRAMStart an input program: commands that build the cases of a new active dataset.
END INPUT PROGRAMEnd an input program and run it.
END CASEIn an input program: add the case built so far to the dataset and go on.
END FILEIn an input program or FILE TYPE: stop reading; the case being built is dropped.
REREADIn an input program: let the next DATA LIST read the last record again.
REPEATING DATAIn an input program or FILE TYPE: one case per repeating group of a record.
FILE TYPEStart the definition of a file with several kinds of records.
RECORD TYPEInside FILE TYPE: the record types the following DATA LIST reads.
END FILE TYPEEnd a FILE TYPE definition and read the file.
SPLIT FILERun each procedure once per run of consecutive cases that share the split values.
FILTERLeave out of procedures the cases whose filter value is 0 or missing.
TEMPORARYMake the changes that follow last only until the next procedure.
N OF CASESKeep only the first n cases from the next data pass on.
NShort for N OF CASES.
SAMPLEKeep a random sample of the cases.
BOOTSTRAPGive the next procedure bootstrap bias, standard errors and confidence intervals.

Transformations

命令功能 {#what-it-does}
COMPUTEAssign the value of an expression to a variable.
IFAssign a value only for the cases where a condition holds.
DO IFStart a block of transformations that run only where a condition holds.
ELSE IFStart the next conditional branch of a DO IF block.
ELSEStart the branch of a DO IF block for the cases no condition matched.
END IFEnd a DO IF block.
RECODEMap values of variables to new values.
COUNTCount, per case, how many variables hold one of the listed values.
SELECT IFKeep only the cases where a condition holds.
STRINGDeclare new string variables, filled with empty strings.
NUMERICDeclare new numeric variables, filled with system-missing.
LEAVEKeep the values of new variables from case to case instead of resetting them.
EXECUTERun the pending transformations.
DO REPEATRepeat transformations with stand-in names replaced by variables or values.
LOOPRepeat transformations for each case, with an index, a condition or both.
END LOOPEnd a LOOP, optionally when a condition holds.
BREAKLeave the innermost LOOP, usually inside DO IF.
VECTORName a range of variables, or new variables, as a vector for indexed use.
AUTORECODERecode values into consecutive integers in new variables, labeled with the old values.
RANKRanks, percentile groups, proportion estimates, normal and Savage scores as new variables.
DATEAdd date variables that count the cases of a time series.
PRINTShow the values of variables for every case, as lines of text.
PRINT EJECTLike PRINT, starting a new page each time it runs.
PRINT SPACEAdd blank lines to the PRINT output, for every case it runs on.
WRITEWrite the values of variables for every case to a text file.
CLEAR TRANSFORMATIONSUndo the transformations and dictionary changes since the last data pass.

Procedures

命令功能 {#what-it-does}
FREQUENCIESFrequency tables, summary statistics and percentiles.
DESCRIPTIVESSummary statistics of numeric variables, optionally saved as z-scores.
CROSSTABSContingency tables with percentages, residuals and chi-square tests.
MULT RESPONSEFrequency tables and crosstabulations of multiple response groups and variables.
MEANSStatistics of dependent variables within groups of control variables.
SUMMARIZEStatistics of dependents within groups of control variables, optionally listing the cases.
OLAP CUBESStatistics of scale variables in nested groups, with differences between groups or variables.
CODEBOOKDictionary entries and summary statistics of variables and multiple response sets.
VALIDATEDATAFind suspicious variables, incomplete or duplicate IDs, empty cases and rule violations.
T-TESTOne-sample, independent-samples and paired-samples t tests with effect sizes.
ONEWAYOne-way analysis of variance with contrasts and post hoc comparisons.
CORRELATIONSPearson correlations with significance and case counts.
NONPAR CORRSpearman’s rho and Kendall’s tau-b rank correlations with significance.
PARTIAL CORRPartial correlations of variables controlling for others, with significance.
NPAR TESTSNonparametric tests: one-sample, two and k related samples, two and k independent samples.
NPTESTSNonparametric tests picked by measurement level: one sample, independent samples, related samples.
PROPORTIONSTests and confidence intervals for a proportion or a difference of two proportions.
EXAMINEDescriptives, percentiles, M-estimators, extreme values and normality tests, by factor cells.
REGRESSIONLinear regression with forced entry or removal and stepwise selection, residuals and diagnostics.
RELIABILITYReliability of a scale: Cronbach’s alpha, split-half and other models, item statistics and ICC.
WEIGHTED KAPPACohen’s weighted kappa: how well two raters agree on an ordered scale.
FLEISS MULTIRATER KAPPAFleiss’ kappa: how well several raters agree when they sort subjects into categories.
RATIO STATISTICSStatistics of the ratio of two positive variables, overall and within groups.
BAYES ONESAMPLEBayesian inference on one mean, proportion or Poisson rate: Bayes factors and posteriors.
BAYES RELATEDBayesian inference on the mean difference of paired measurements.
BAYES INDEPENDENTBayesian comparison of the means of two independent groups.
BAYES CORRELATIONBayesian inference on the Pearson correlation of every pair of variables.
BAYES ANOVABayesian one-way analysis of variance: a Bayes factor for the groups and posteriors of their means.
BAYES REGRESSIONBayesian linear regression: a Bayes factor for the model, posteriors, predictions and F tests.
BAYES REPEATEDBayesian one-way repeated measures analysis: a Bayes factor and posteriors of the condition means.
BAYES LOGLINEARBayesian test of independence in a two-way table, with simulated interaction terms.
POWER MEANS ONESAMPLEPower or sample size of a one-sample t-test of a mean.
POWER MEANS INDEPENDENTPower or group sizes of a t-test comparing the means of two independent groups.
POWER MEANS RELATEDPower or number of pairs of a paired t-test.
POWER PROPORTIONS ONESAMPLEPower or sample size of a test of one proportion against a hypothesized value.
POWER PROPORTIONS INDEPENDENTPower or group sizes of a test comparing two independent proportions.
POWER PROPORTIONS RELATEDPower or number of pairs of McNemar’s test of two paired proportions.
POWER ONEWAY ANOVAPower or group sizes of a one-way analysis of variance, its contrasts and pairwise comparisons.
POWER PEARSON ONESAMPLEPower or sample size of a test of one Pearson correlation against a hypothesized value.
POWER SPEARMAN ONESAMPLEPower or sample size of a test of one Spearman rank correlation against a hypothesized value.
POWER PARTIALCORRPower or sample size of a test of one partial correlation against a hypothesized value.
POWER UNIVARIATE LINEARPower or sample size of the F test of a set of predictors in a linear regression.
SIMPLANA simulation plan: distributions of the inputs, fitted to the data or given, their correlations and the targets of a model.
SIMRUNRuns a simulation plan: draws the inputs, computes the targets and describes their distributions.
BEGIN EXPRStarts a block of expressions that END EXPR saves as a model for SIMPLAN.
END EXPREnds the BEGIN EXPR block and writes its model file.
FACTORFactor analysis: principal components and six factoring methods, rotations, factor scores.
QUICK CLUSTERK-means clustering of cases into a given number of clusters.
CLUSTERHierarchical clustering of cases by one of 37 proximity measures and seven methods.
TWOSTEP CLUSTERClusters of cases from continuous and categorical variables, the number of clusters chosen by BIC or AIC.
DMCLUSTERAnother name for TWOSTEP CLUSTER.
DETECTANOMALYUnusual cases: peer groups by two-step clustering, an anomaly index and the variables behind it.
OPTIMAL BINNINGBins of scale variables: cuts chosen by MDLP against a guide variable, or by equal frequency.
KNNNearest neighbor analysis: classify or predict a target from the k most similar training cases.
NAIVEBAYESNaive Bayes classification of a categorical target, with forward selection of the predictors.
AIMAttribute importance: how much each variable sets every group (cluster) apart from all cases.
SELECTPREDScreens a long list of predictors and ranks them one by one by how well each relates to a target.
RESPONSE RATEResponse rates of a numerator over a denominator in each group, with cumulative rates and limits.
ADPPrepares a target and its inputs for modelling and writes the preparation as syntax.
PROXIMITIESSimilarities, dissimilarities or distances between cases or variables by one of 37 measures.
PROXSCALMultidimensional scaling of one or more proximity matrices by majorization, with optimal transformations.
PREFSCALMultidimensional unfolding of preferences or proximities between row and column objects, with penalized stress.
ALSCALMultidimensional scaling of proximity matrices, symmetric, asymmetric or rectangular, by alternating least squares on squared distances.
ORTHOPLANGenerates an orthogonal main-effects plan of profiles for a conjoint study.
PLANCARDSShows the profiles of a conjoint plan as a list or as one card per profile.
CONJOINTPart-worth utilities and importances from rankings or scores of the profiles of a plan.
DISCRIMINANTLinear discriminant analysis with direct or stepwise entry and classification of cases.
CORRESPONDENCECorrespondence analysis: rows and columns of a two-way table as points in a few dimensions.
MULTIPLE CORRESPONDENCEMultiple correspondence (homogeneity) analysis: cases and categories of several nominal variables as points in a few dimensions.
CATPCACategorical principal components: quantify each variable by optimal scaling (spline, ordinal, nominal, multiple nominal or numeric) and reduce them to a few components.
CATREGCategorical regression: quantify a response and its predictors by optimal scaling (spline, ordinal, nominal or numeric) so that a linear model fits best, with ridge, lasso and elastic net penalties.
HOMALSHomogeneity analysis in the older syntax: MULTIPLE CORRESPONDENCE with variables read as categories 1 to a stated largest value.
PRINCALSNonlinear principal components in the older syntax: CATPCA with variables read as categories 1 to a stated largest value.
OVERALSNonlinear canonical correlation analysis: what two or more sets of variables, each quantified at its own level, have in common.
ANACORCorrespondence analysis in the older syntax: CORRESPONDENCE with its own normalization names and defaults.
LOGISTIC REGRESSIONBinary logistic regression with categorical covariates, stepwise selection and case diagnostics.
DMLOGISTICAnother name for LOGISTIC REGRESSION.
NOMREGMultinomial logistic regression: a nominal dependent variable on factors and covariates.
MVAMissing value analysis: where values are missing, how that relates to the other variables, and estimates that allow for it.
HILOGLINEARHierarchical loglinear models of a multiway table of counts, with backward elimination.
LOGLINEARGeneral loglinear and logit models of a table of counts, with contrasts, cell weights and generalized residuals.
GENLOGGeneral loglinear and logit models of a table of counts, with cell weights, covariates and contrasts.
PROBITProbit and logit models of response counts out of subject counts, with effective levels.
CURVEFITFit up to eleven curves of one independent variable, or of time, by least squares.
WLSWeighted least squares: weights from a power of a source variable, or a given weight.
MODEL PROGRAMName the parameters of a nonlinear model and give their starting values; the transformations after it define the model.
DERIVATIVESStart the derivatives program of the model program.
CLEAR MODEL PROGRAMSDrop the model program and the derivatives program of the last MODEL PROGRAM.
NLRNonlinear regression by least squares (Levenberg-Marquardt) for the model of the last MODEL PROGRAM.
CONSTRAINED FUNCTIONSStart the program that computes the constrained functions of the next CNLR.
CNLRConstrained nonlinear regression: least squares or a loss function of your own, under bounds, linear constraints and constrained functions.
MULTIPLE IMPUTATIONMultiple imputation: several completed copies of the data with plausible values in place of the missing ones.
PLUMOrdinal regression: a cumulative link model of an ordered dependent variable.
QUANTILE REGRESSIONLinear regression of a chosen quantile of the dependent variable, fitted by linear programming.
PLSPartial least squares regression of one or more dependent variables on many, possibly collinear, predictors.
GENLINGeneralized linear models: normal, binomial, Poisson, gamma, inverse Gaussian, negative binomial and ordinal responses.
UNIANOVAGeneral linear model of one dependent variable: factorial ANOVA, ANCOVA and regression.
GLMGeneral linear model: one dependent variable as in UNIANOVA, several (multivariate analysis of variance and covariance), or repeated measures with WSFACTOR.
MANOVAAnalysis of variance and covariance for one or several dependents, with nested and pooled terms, partitions and chosen error terms.
MIXEDLinear mixed model: fixed effects with random effects of subjects and correlated repeated measures.
VARCOMPVariance components: how much each random effect of a linear model adds to the variance of the dependent variable.
GENLINMIXEDGeneralized linear mixed model: a target with a normal, binomial, multinomial, gamma, inverse Gaussian, Poisson or negative binomial distribution and a link, fixed effects, random effects of subjects and repeated measures.
COXREGCox proportional hazards regression of survival times, with strata, categorical covariates, stepwise selection and time-dependent covariates.
TIME PROGRAMStart the transformations that define time-dependent covariates for the next COXREG.
CLEAR TIME PROGRAMDrop the time-dependent covariates of the last TIME PROGRAM.
ANOVAAnalysis of variance for factorial designs with covariates, the older form with MCA tables.
TREEA decision tree grown by CHAID, exhaustive CHAID, CRT or QUEST, with gain tables, rules and saved predictions.
DMTREEAnother name for TREE.
MLPMultilayer perceptron: a neural network with one or two hidden layers that predicts scale dependents and classifies categorical ones.
RBFRadial basis function network: Gaussian hidden units at two-step clusters and least squares output weights.
GRAPHOne chart: summaries by category as bars, lines, areas, a pie, points with error bars, a Pareto chart or ranges, a histogram, a scatterplot or a scatterplot matrix.
GGRAPHA chart from a graph dataset and a chart program in BEGIN GPL: bars (clustered, stacked), lines, areas, points, a pie or a histogram.
BEGIN GPLThe chart program of the GGRAPH command right before it, up to END GPL.
IGRAPHThe older chart command: bars, lines, areas, pies, boxes, error bars, histograms and scatterplots built from variables placed on axes and legends.
XGRAPHCharts from one expression: summaries as bars or lines, clustered, stacked and paneled, population pyramids, binned histograms, dot plots and boxes.
PPLOTProbability plots: Q-Q or P-P plots of variables against a test distribution.
NPPLOTAnother name for PPLOT.
ROCROC curve of test variables against a state, with the area under the curve.
DMROCAnother name for ROC.
ROC ANALYSISROC curves with paired or two-group comparisons of their areas, precision-recall curves and classifier metrics.
SPCHARTControl charts (X-bar with R or s, individuals, p, np, c, u) and the process capability chart.
KMKaplan-Meier survival estimates by factor level and stratum, with tests that compare the levels.
K-MAnother name for KM.
SURVIVALActuarial life tables over fixed time intervals, with the Wilcoxon (Gehan) comparison of groups.
REPORTCase listings and summary statistics by break groups, laid out as a report.
MATRIXRun a program in the matrix language, up to END MATRIX.

Time series

命令功能 {#what-it-does}
TSETSettings shared by the time series procedures.
TSHOWList the time series settings.
VERIFYCheck the DATE variables and report the USE and PREDICT periods.
CREATENew series from functions of existing series: lags, differences, smoothers, FFT.
RMVCopies of series with the missing values filled in by interpolation, a mean, a median or a trend.
ACFAutocorrelations of time series, with standard errors, Box-Ljung tests and charts.
PACFPartial autocorrelations of time series, with standard errors and charts.
CCFCross-correlations of pairs of time series, with standard errors and charts.
SEASONSeasonal decomposition by ratios (or differences) to a moving average.
PREDICTSet the forecast period of EXSMOOTH and ARIMA.
EXSMOOTHExponential smoothing with or without trend and season, with fitted values and forecasts.
ARIMASeasonal ARIMA models with regressors by exact maximum likelihood, with forecasts.
AREGRegression whose errors follow a first-order autoregressive process.
SPECTRAPeriodogram, smoothed spectral density and cross-spectra of series.
2SLSTwo-stage least squares for equations with endogenous predictors.
TSMODELExponential smoothing and ARIMA models of series, picked by hand or by the expert modeler, with forecasts.
TSAPPLYForecasts from time series models that TSMODEL saved, as they are or estimated again.
TSPLOTChart of time series over the cases, as chart data.
CASEPLOTChart of time series with the cases down the vertical axis, as chart data.
FITGoodness-of-fit statistics of residual series from time series models.

自定义表格

命令功能 {#what-it-does}
CTABLESCustom tables: counts, percentages and statistics by categories.
DMTABLESAnother name for CTABLES.
MRSETSDefine, delete and list multiple response sets.

Complex samples

命令功能 {#what-it-does}
CSPLANWrite or show the plan of a complex sample: how to draw it, or how to analyze it.
CSSELECTDraw a complex sample from the active dataset by a plan written by CSPLAN SAMPLE.
CSDESCRIPTIVESMeans, sums and ratios of a complex sample with design-based standard errors and design effects.
CSTABULATEOne-way and two-way tables of a complex sample with design-based errors and adjusted tests.
CSGLMLinear regression, ANOVA and ANCOVA on a complex sample, with design-based standard errors and tests.
CSLOGISTICBinary and multinomial logistic regression on a complex sample, with design-based standard errors and tests.
CSORDINALOrdinal regression (cumulative link model) on a complex sample, with design-based standard errors and tests.
CSCOXREGCox proportional hazards regression on a complex sample, with design-based standard errors and tests.

Macros, files and session

命令功能 {#what-it-does}
DEFINEDefine a macro: a name that stands for syntax, with arguments.
INSERTRun the commands of another syntax file in place of this command.
INCLUDERun the commands of another syntax file, read by the batch rules.
BEGIN PROGRAMA block of code in another programming language; it is skipped with a warning.
SETChange settings of the session.
SHOWShow the current settings.
PRESERVEStore the current settings and folder, to bring them back with RESTORE.
RESTOREBring back the settings and folder the last PRESERVE stored.
CACHEAccepted and has nothing to do: the data are always kept in memory.
CDChange the folder relative file names start from.
PROCEDURE OUTPUTName the file the next procedures write their results to.
FILE HANDLEGive a file or a folder a short name to use in place of its path.
DATASET NAMEGive the active dataset a name, so that it stays open when another one becomes active.
DATASET ACTIVATEMake a named dataset the active one.
DATASET COPYCopy the active dataset, as it is now, into a named dataset.
DATASET DECLAREReserve a dataset name for a dataset that a later command creates.
DATASET CLOSEClose a named dataset, or take the name off the active one.
DATASET DISPLAYList the open datasets.
USESet the historical period of the time series procedures, or use all cases.
DISPLAYShow dictionary information of the active dataset.
LISTList the values of cases.
TITLEPut a title in the output, above the output that follows.
SUBTITLEPut a subtitle in the output, above the output that follows.
ECHOShow a text in the output.
ERASEDelete a file.
PERMISSIONSMake a file read-only, or writeable for its owner.
HOSTRefused: Statscraft never runs operating system commands from syntax.
OUTPUT NEWStart a new output document, which gets the tables from now on.
OUTPUT NAMEName the output document that gets the tables.
OUTPUT ACTIVATESend the tables from now on to an open output document.
OUTPUT CLOSEClose an output document, or all of them.
OUTPUT DISPLAYList the open output documents.
OUTPUT EXPORTWrite the tables and charts of an output document to a workbook, document, presentation, PDF, web page, text or CSV file.
OUTPUT SAVESave an output document as a Statscraft output file (.scout).
OUTPUT OPENOpen a Statscraft output file (.scout) as a new output document.
OUTPUT MODIFYDelete, hide, rename, sort, transpose or reformat items of an output document.
OMSSend the tables, charts and warnings of the commands that follow to a file, or keep them out of the results.
OMSENDEnd OMS requests and the OMS log.
OMSINFOList the OMS requests in force.
OMSLOGKeep a log of when OMS requests start and end and which files they write.
BEGIN CHARTA Statscraft extension: a chart given as JSON goes to the output like a procedure’s chart.
FINISHEnd the job: the commands after it are not read.

General rules of the language

  A command ends at a line whose last character is a period, at a blank line, or at the end of input.
  Command names and keywords are case-insensitive and may be shortened to three or more letters.
  varlist: variable names, a range written as first TO last, or ALL.
  Strings use single or double quotes; double the quote character to include it. A string may
  run on over line breaks, which it keeps; 'a' + 'b' joins two strings into one.
  Comments: a command starting with * or COMMENT, or /* text */ inside a line.
  Expressions: + - * / **, = <> < > <= >= (or EQ NE LT GT LE GE), AND OR NOT (or & | ~),
  functions such as MEAN(a, b) or SUM(q1 TO q5); LAG(var [, n]) is the value n cases back.
  A function name may be shortened to three or more letters that start no other function.
  An expression nests at most 64 levels of parentheses and functions and holds at most 1500 operators (use SUM(x1 TO x2000) for a longer sum).
  Scratch variables start with #: they begin at 0 or blank, keep their value from case to case,
  are never saved and are gone when the next procedure starts. System variables: $CASENUM
  is the case number, $SYSMIS the system-missing value, $JDATE today as a day count (1 is
  15 October 1582), $DATE and $DATE11 today as dd-mmm-yy and dd-mmm-yyyy text, $TIME now in
  seconds (a date value), $LENGTH and $WIDTH the SET LENGTH and WIDTH.

Functions of expressions (COMPUTE, IF, SELECT IF, DO IF, ELSE IF, LOOP IF, END LOOP IF):
  Arithmetic: ABS RND TRUNC MOD SQRT EXP LN LG10 LNGAMMA SIN COS TAN ARSIN ARCOS ARTAN.
  Statistical, with .n for the valid values needed (MEAN.2): SUM MEAN MEDIAN MIN MAX SD VARIANCE
  CFVAR. Missing values: MISSING SYSMIS VALUE NMISS NVALID. Logical: ANY RANGE. Also LAG and
  VALUELABEL.
  Strings: CONCAT LENGTH CHAR.LENGTH UPCASE LOWER LTRIM RTRIM NTRIM SUBSTR CHAR.SUBSTR INDEX
  CHAR.INDEX RINDEX CHAR.RINDEX LPAD CHAR.LPAD RPAD CHAR.RPAD REPLACE STRUNC CHAR.MBLEN
  MBLEN.BYTE NORMALIZE NUMBER STRING.
  Dates and times: DATE.DMY DATE.MDY DATE.MOYR DATE.QYR DATE.WKYR DATE.YRDAY YRMODA TIME.DAYS
  TIME.HMS CTIME.DAYS CTIME.HOURS CTIME.MINUTES CTIME.SECONDS XDATE.DATE XDATE.HOUR XDATE.JDAY
  XDATE.MDAY XDATE.MINUTE XDATE.MONTH XDATE.QUARTER XDATE.SECOND XDATE.TDAY XDATE.TIME
  XDATE.WEEK XDATE.WKDAY XDATE.YEAR DATEDIFF DATESUM (units years quarters months weeks days
  hours minutes seconds; DATESUM methods 'closest', the default, and 'rollover').
  Distributions: CDFNORM PROBIT, and CDF.d IDF.d PDF.d NCDF.d NPDF.d SIG.d RV.d where the
  distribution d has them: BERNOULLI BETA BINOM BVNOR CAUCHY CHISQ EXP F GAMMA GEOM HALFNRM HYPER
  IGAUSS LAPLACE LNORMAL LOGISTIC NEGBIN NORMAL PARETO POISSON SMOD SRANGE T UNIFORM WEIBULL
  (NCDF and NPDF: BETA CHISQ F T; SIG: CHISQ F). UNIFORM(max), NORMAL(sd) and the RV functions
  draw random numbers. An argument out of range gives system-missing.

Statscraft 0.61.0, release v0.61.0

Data files and dictionary

命令功能 {#what-it-does}
GETRead a data file and make it the active dataset.
GET DATARead a text data file, a sheet of a workbook or a dataset of an OpenStatSpec database as the active dataset.
GET TRANSLATERead a tab-delimited text file, a dBASE file or an old Excel workbook.
GET STATARead a Stata data file (.dta) and make it the active dataset.
IMPORTRead a portable (.por) file and make it the active dataset.
SYSFILE INFOShow the dictionary of a data file without opening it as the active dataset.
SAVEWrite the active dataset to a data file.
SAVE TRANSLATEWrite the active dataset to a CSV or tab-delimited text file, an Excel workbook, a Stata file, a SAS transport file or a dBASE file.
SAVE CODEPAGEWrite the active dataset to a data file whose text is in a code page.
EXPORTWrite the active dataset to a portable (.por) file.
XSAVEWrite the cases to a data file as the next data pass reads them.
NEW FILEStart a new, empty active dataset.
ADD CASEA Statscraft extension: one blank case after the last case of the active dataset.
ADD FILESAppend the cases of several data files, matching variables by name.
MATCH FILESCombine the variables of several data files case by case or by key.
STAR JOINAdd the fields of lookup files to every case of a data file, by keys, as an SQL left join.
UPDATEReplace values of a primary file with the values of transaction files, by key.
COMPARE DATASETSCompare the values and dictionary of the active dataset with another dataset or .sav file.
VARIABLE LABELSSet the labels of variables.
VALUE LABELSReplace the value labels of variables.
MISSING VALUESDeclare user-missing values.
VARIABLE LEVELSet the measurement level of variables.
VARIABLE WIDTHSet how many characters wide variables show in the data grid.
FORMATSSet the display format of variables.
PRINT FORMATSSet the print format of variables: how procedures and PRINT show them.
WRITE FORMATSSet the write format of variables: how WRITE writes them.
RENAME VARIABLESChange the names of variables.
DELETE VARIABLESRemove variables from the dataset.
SORT CASESSort the cases by the values of variables.
SORT VARIABLESPut the variables in order by a property of their dictionary entries.
SHIFT VALUESNew variables that hold the value of the same variable in an earlier or later case.
WEIGHTWeight the cases by a variable, or turn weighting off.
AGGREGATEAggregate groups of cases into new variables or a new dataset.
VARSTOCASESTurn groups of variables into cases: one new case per variable of the group.
CASESTOVARSTurn groups of cases into one case each, with a variable per value of an index.
FLIPTranspose the data: variables become cases and cases become variables.
ADD VALUE LABELSAdd or change value labels, keeping the other labels of the variables.
FILE LABELSet the label of the data file.
DOCUMENTAdd free text to the documents of the data file.
ADD DOCUMENTAdd quoted lines to the documents of the data file.
DROP DOCUMENTSRemove the documents of the data file.
VARIABLE ROLESet the role of variables for dialogs.
VARIABLE ALIGNMENTSet the alignment of variables in the data grid.
VARIABLE ATTRIBUTESet or delete custom attributes of variables.
DATAFILE ATTRIBUTESet or delete custom attributes of the data file.
ALTER TYPEChange the type, string width or format of variables.
APPLY DICTIONARYCopy dictionary information from a data file or dataset to the active dataset.
DATA LISTDefine text data, inline or in a file, and read it as the new active dataset.
KEYED DATA LISTRead variables from the record of a text file that a key variable picks, for each case.
BEGIN DATAInline data for the DATA LIST before it, up to a line that holds END DATA.
MATRIX DATARead matrix materials (correlations, means, counts) as a matrix data file.
MCONVERTMatrix data between covariances and correlations with standard deviations.
INPUT PROGRAMStart an input program: commands that build the cases of a new active dataset.
END INPUT PROGRAMEnd an input program and run it.
END CASEIn an input program: add the case built so far to the dataset and go on.
END FILEIn an input program or FILE TYPE: stop reading; the case being built is dropped.
REREADIn an input program: let the next DATA LIST read the last record again.
REPEATING DATAIn an input program or FILE TYPE: one case per repeating group of a record.
FILE TYPEStart the definition of a file with several kinds of records.
RECORD TYPEInside FILE TYPE: the record types the following DATA LIST reads.
END FILE TYPEEnd a FILE TYPE definition and read the file.
SPLIT FILERun each procedure once per run of consecutive cases that share the split values.
FILTERLeave out of procedures the cases whose filter value is 0 or missing.
TEMPORARYMake the changes that follow last only until the next procedure.
N OF CASESKeep only the first n cases from the next data pass on.
NShort for N OF CASES.
SAMPLEKeep a random sample of the cases.
BOOTSTRAPGive the next procedure bootstrap bias, standard errors and confidence intervals.

All commands

Statscraft 0.61.0, release v0.61.0

GET

Read a data file and make it the active dataset.

Syntax

GET FILE='path' | handle [/KEEP=varlist] [/DROP=varlist] [/RENAME=(old = new) ...] [/MAP].

KEEP, DROP and RENAME work in the order written, as in ADD FILES. MAP lists the variables as the options before it leave them, each with its name in the file; it may come as often as you like.

Example

GET FILE='survey.sav'.
GET FILE='survey.sav' /KEEP=id region satisfaction spend.
GET FILE='survey.sav' /DROP=ch_web TO ch_email /RENAME=(spend = monthly_bill) /MAP.

The example reads the sample data file survey.sav, an invented customer survey; save it in the folder you run the syntax from.

Example output

Variables in the active dataset

VariableName in the file
idid
regionregion
gendergender
ageage
age_groupage_group
educationeducation
weightweight
satisfactionsatisfaction
recommendrecommend
contactedcontacted
switchingswitching
monthly_billspend
interview_dateinterview_date

statscraft help GET prints the same text in the terminal. All commands

Statscraft 0.61.0, release v0.61.0

GET DATA

Read a text data file, a sheet of a workbook or a dataset of an OpenStatSpec database as the active dataset.

Syntax

GET DATA /TYPE=TXT /FILE='path' [/ENCODING='name'] [/ARRANGEMENT=DELIMITED | FIXED]
         [/FIRSTCASE=n] [/DELCASE=LINE | VARIABLES n] [/FIXCASE=n] [/DELIMITERS="chars"]
         [/QUALIFIER="c"] [/IMPORTCASE=ALL | FIRST n] [/MULTIPLESPACES IGNORE=NO | YES]
         [/LEADINGSPACES IGNORE=NO | YES]
         /VARIABLES=name format [name format ...] [/MAP].
GET DATA /TYPE=XLSX | XLSM | XLS /FILE='path' [/SHEET=INDEX n | NAME 'name']
         [/CELLRANGE=FULL | RANGE 'A1:K14'] [/READNAMES=ON | OFF] [/ASSUMEDSTRWIDTH=n]
         [/HIDDEN IGNORE=NO | YES] [/LEADINGSPACES IGNORE=NO | YES]
         [/TRAILINGSPACES IGNORE=NO | YES] [/DATATYPEMIN PERCENTAGE=n].
GET DATA /TYPE=OPENSTATSPEC /DATABASE=SQLITE | POSTGRES | MYSQL | DOLT 'file or URL'
         /DATASET=name [/ALLOWLOSS=NO | YES].

Text files. FIXED: /VARIABLES=[/record] name first-last format …, columns counted from 0.

format: F, A, DATE, ADATE, SDATE, DATETIME, DOLLAR, COMMA and the other input formats, with or without a width; AUTO reads a number when DATATYPEMIN PERCENTAGE (95 unless given) of the non-blank values are numbers, the others becoming system-missing, else a string as wide as the longest value; in fixed columns the decimals of a number format are implied when the value has no decimal point, as in DATA LIST; X skips the field. DELIMITERS: \t is a tab, \\ a backslash; two delimiters in a row leave a value empty. Default delimiters: tab and comma. A value between qualifiers may hold delimiters and line breaks; a doubled qualifier is one. SET DECIMAL=COMMA reads a comma as the decimal mark: F, E and PCT take that mark only (a period there makes the value system-missing), COMMA and DOLLAR a period, DOT a comma. ENCODING as for INSERT; a byte order mark wins. MAP, the only subcommand allowed after VARIABLES, is accepted and shows nothing.

Workbooks (XLSX and XLSM from Excel 2007 on, XLS from Excel 95 to 2003). The first sheet by default; FULL reads from the first to the last cell with a value. READNAMES=ON (default) takes the first row as names, made valid: other characters become _, a name that does not start with a letter gets a V in front, a repeated one _2; OFF and an empty heading give V1, V2, … by the column in the range. A column is numeric (F, 0 or 2 decimals) when all its values are numbers (TRUE and FALSE are 1 and 0), a date when all are dates or times (DATE11, TIME8 or DATETIME20), else a string as wide as its longest value. DATATYPEMIN PERCENTAGE=n (over 50) lets the kind of n percent of the values decide; the others become system-missing.

Empty rows and empty columns without a name are left out; error cells are empty. HIDDEN IGNORE=YES leaves out hidden rows and columns (XLSX only). ASSUMEDSTRWIDTH cuts longer strings (XLS: 255 by default). LEADINGSPACES IGNORE=YES removes leading blanks of strings; TRAILINGSPACES IGNORE=YES leaves trailing blanks out of the width.

Databases. OPENSTATSPEC reads a dataset that statscraft db export stored. SQLITE takes a file, the others a server URL written as for statscraft db (MYSQL also serves MariaDB).

Syntax never holds a password: a URL with one is refused, and the password comes from the STATSCRAFT_DB_PASSWORD environment variable of the program that runs the syntax; the window reads it from its own environment. ALLOWLOSS=YES goes on when the catalog holds items the dataset cannot keep, with a warning for each. The read is logged in the catalog, as for statscraft db import, except on DOLT, where nothing is written and a table names the branch and HEAD commit that were read; uncommitted changes there give a warning.

Example

GET DATA /TYPE=TXT /FILE='wave2.csv' /DELIMITERS="," /QUALIFIER='"' /FIRSTCASE=2
  /VARIABLES=id F5 name A20 born SDATE10.
GET DATA /TYPE=XLSX /FILE='wave3.xlsx' /SHEET=NAME 'Answers' /CELLRANGE=RANGE 'A1:F200'.
GET DATA /TYPE=OPENSTATSPEC /DATABASE=SQLITE 'panel.db' /DATASET=wave_4.

statscraft help GET DATA prints the same text in the terminal. All commands

Statscraft 0.61.0, release v0.61.0

GET TRANSLATE

Read a tab-delimited text file, a dBASE file or an old Excel workbook.

Syntax

GET TRANSLATE FILE='path' | handle [/TYPE=TAB | DBF | XLS] [/FIELDNAMES]
              [/RANGE=A1..K14 | 'A1:K14'] [/KEEP=varlist] [/DROP=varlist]
              [/RENAME=(old = new) ...] [/MAP].

TYPE may be left out for a .tab, .dbf or .xls file. KEEP and DROP do not change the order of the variables. FIELDNAMES takes the names from the first row (of the range); they are made valid: other characters become _, a reserved word gets $ (GE$), a repeated name a number, and a column without a name is left out. RANGE limits the rows and columns.

TAB: rows end with a line break and values with a tab. Names are VAR1, VAR2, …

without FIELDNAMES. The first value of a column decides its type: a number gives F8.2 or wider, any other text a string of at least 8 bytes, as wide as that value; longer values are cut, and text in a numeric column is system-missing.

DBF (dBASE II, III and IV): every record, also those marked deleted, which get * in an added string D_R. Character and logical fields are strings, numeric and float fields numbers (F with the field’s width and decimals), date fields dates (DATE11); memo fields are left out. FIELDNAMES is ignored.

XLS (Excel 95 to 2003, read as GET DATA reads it): the first sheet; names are the column letters without FIELDNAMES.

Example

GET TRANSLATE FILE='address.dbf' /DROP=phoneno entry /MAP.
GET TRANSLATE FILE='wave3.txt' /TYPE=TAB /FIELDNAMES.

statscraft help GET TRANSLATE prints the same text in the terminal. All commands

Statscraft 0.61.0, release v0.61.0

GET STATA

Read a Stata data file (.dta) and make it the active dataset.

Syntax

GET STATA FILE='path' | handle [/ENCODING='name'].

Reads formats 113 to 119 (Stata 8 to 19), in either byte order. ENCODING names the code page of text in files older than Stata 14 (LOCALE and SYSTEM: the system’s); without it such text is UTF-8 when it reads as UTF-8, else in the system’s code page. Newer files are always UTF-8.

Names keep their case; one that differs from an earlier one only in case gets _A, _B, …, one that starts with _ gets V in front and a reserved word gets $. Variable labels, value labels and the file label (cut to 64 bytes) come along. Every Stata missing value, . and .a to .z, is system-missing, and labels of .a to .z are dropped. %td dates become DATE11 and %tc and %tC datetimes DATETIME20; weekly, monthly, quarterly, half-yearly and yearly values stay counts since 1960 in F format. Long strings (strL) become strings of up to 32767 bytes; one holding binary data is blank.

Example

GET STATA FILE='clinic.dta'.
GET STATA FILE='panel2009.dta' /ENCODING='windows-1257'.

statscraft help GET STATA prints the same text in the terminal. All commands

Statscraft 0.61.0, release v0.61.0

IMPORT

Read a portable (.por) file and make it the active dataset.

Syntax

IMPORT FILE='path' | handle [/TYPE=COMM | TAPE] [/KEEP=varlist] [/DROP=varlist]
       [/RENAME=(old = new) ...] [/MAP].

KEEP, DROP and RENAME work in the order written, as in GET; KEEP sets the order of the variables. Each MAP shows the variables as the subcommands before it leave them. The file’s weight variable weights the cases. TYPE is accepted and changes nothing.

Example

IMPORT FILE='wave2.por' /DROP=dept TO division /MAP.

statscraft help IMPORT prints the same text in the terminal. All commands

Statscraft 0.61.0, release v0.61.0

SYSFILE INFO

Show the dictionary of a data file without opening it as the active dataset.

Syntax

SYSFILE INFO [FILE=] 'path'.

A table of the file (label, cases, variables, documents) and the tables of DISPLAY DICTIONARY.

Example

SYSFILE INFO FILE='survey.sav'.

The example reads the sample data file survey.sav, an invented customer survey; save it in the folder you run the syntax from.

statscraft help SYSFILE INFO prints the same text in the terminal. All commands

Statscraft 0.61.0, release v0.61.0

SAVE

Write the active dataset to a data file.

Syntax

SAVE OUTFILE='path' | handle [/COMPRESSED | /UNCOMPRESSED | /ZCOMPRESSED] [/KEEP=varlist] [/DROP=varlist]
     [/RENAME=(old = new) ...] [/MAP].

KEEP, DROP and RENAME shape the saved file only; the active dataset stays as it is. MAP lists the variables of the file as the options before it leave them, each with its name in the active dataset; it may come as often as you like.

COMPRESSED compresses case by case, ZCOMPRESSED in zlib blocks, UNCOMPRESSED not at all; without one a file named .zsav gets zlib blocks and any other the case by case form.

Example

GET FILE='survey.sav'.
SAVE OUTFILE='survey_copy.sav'.
SAVE OUTFILE='satisfaction.sav' /KEEP=id region satisfaction /RENAME=(satisfaction = sat) /MAP.

The example reads the sample data file survey.sav, an invented customer survey; save it in the folder you run the syntax from.

Example output

Variables in the file

Name in the fileVariable
idid
regionregion
satsatisfaction

statscraft help SAVE prints the same text in the terminal. All commands

Statscraft 0.61.0, release v0.61.0

SAVE TRANSLATE

Write the active dataset to a CSV or tab-delimited text file, an Excel workbook, a Stata file, a SAS transport file or a dBASE file.

Syntax

SAVE TRANSLATE OUTFILE='path' | handle /TYPE=CSV | TAB | XLS /VERSION=12 | STATA | SAS /VERSION=X | DB3 | DB4 [/REPLACE]
    [/FIELDNAMES [VALUE=NAMES | LABELS]] [/CELLS=VALUES | LABELS] [/MISSING=IGNORE | RECODE]
    [/TEXTOPTIONS [DELIMITER='c'] [QUALIFIER='c'] [DECIMAL=DOT | COMMA] [FORMAT=PLAIN | VARIABLE]]
    [/EXCELOPTIONS SHEET='name'] [/ENCODING='name' [BOM=YES | NO]] [/UNSELECTED=RETAIN | DELETE]
    [/KEEP=varlist] [/DROP=varlist] [/RENAME=(old = new) ...] [/MAP]
    [/VERSION=8 to 14] [/EDITION=INTERCOOLED | SE].

TYPE may be left out for a .csv, .xlsx or .dta file; TYPE=XLSX is short for XLS /VERSION=12. An existing file is overwritten only with REPLACE. FIELDNAMES writes a first row of names (VALUE=LABELS: the variable labels, else the names). CELLS=LABELS writes the value label where a value has one. MISSING=RECODE writes user-missing values as empty. UNSELECTED=DELETE leaves out the cases FILTER leaves out. KEEP, DROP and RENAME shape the file only, in the order written; KEEP does not change the order of the variables. Each MAP lists the names in the file next to the names in the dataset, as the subcommands before it leave them.

Text: system-missing is empty. FORMAT=PLAIN (default) writes numbers with the decimals they need, dates as mm/dd/yyyy and times as hh:mm:ss; VARIABLE writes the display formats. The decimal mark is DECIMAL’s, else SET DECIMAL’s. CSV separates values with a comma, or with a semicolon when the decimal mark is a comma, and puts the qualifier (default “) around a value that holds the delimiter, the qualifier (doubled inside) or a line break. TAB never qualifies.

ENCODING as for INSERT; the default is UTF-8 with a byte order mark, which BOM=NO leaves out.

Workbook: numbers keep their display format and dates and times are Excel dates; system-missing is #NULL!. EXCELOPTIONS names the sheet (default Sheet1); more cases than a sheet holds continue on further sheets.

Stata: VERSION is the Stata release that reads the file (default 14; 8 and 9 give format 113, 10 and 11 format 114, 12 format 115, 13 format 117, 14 and later format 118).

INTERCOOLED (the default) keeps up to 2047 variables and 80 bytes of each string; SE keeps 32767 variables and 244 bytes before Stata 13, whole strings from 13 on (over 2045 bytes as strL). Names keep their case: characters other than letters, digits and _ become _, and names are cut to 32 bytes and made unique; before Stata 14 a name that is not ASCII becomes v and its position. Variable labels and the file label keep 80 bytes. Value labels go with numeric variables, for whole values up to 2147483620 (80 bytes each for Stata 8). Dates become %td days since 1960, dates with a time %tc milliseconds; times and other numbers are plain. User-missing values stay valid values unless MISSING=RECODE. Text is UTF-8 from Stata 14 on, else in ENCODING (default: the system’s code page).

SAS: TYPE=SAS /VERSION=X writes a transport file (the layout of version 5, which SAS and other software read); the other SAS versions are not written. Names are cut to 8 bytes, with _ for any other character than a letter or digit, and made unique; the data set is named after the file. The label is the variable label, else the name (40 bytes at most).

Dates are days since 1960-01-01 with the format DATE, dates with a time of day seconds with DATETIME, times seconds with TIME; other numbers have no format. Every missing value, user missing ones too, is the SAS missing value. Text is Windows Latin-1, 200 bytes at most; value labels are not written. ENCODING is not used.

dBASE: DB3 holds 128 fields and DB4 255, a record up to 4000 bytes; more variables are left off with a warning. A field name is the variable name in capitals with _ for any other character than a letter or digit, V in front of a name that does not start with a letter, cut to 10 bytes and made unique. A numeric variable is a numeric field as wide as its print format (19 at most for DB3, 20 for DB4) with its decimals; a missing value, or one that does not fit, is asterisks, so widen the format with PRINT FORMATS first. Dates are date fields (a time of day is dropped); a string variable is a character field of its width, 254 bytes at most, in Windows Latin-1. MISSING=RECODE blanks user-missing values. ENCODING is not used.

Example

SAVE TRANSLATE OUTFILE='wave2.xlsx' /TYPE=XLS /VERSION=12 /FIELDNAMES /CELLS=LABELS /REPLACE.
SAVE TRANSLATE OUTFILE='wave2.csv' /TYPE=CSV /FIELDNAMES /TEXTOPTIONS DECIMAL=COMMA /REPLACE.
SAVE TRANSLATE OUTFILE='clinic.dta' /TYPE=STATA /EDITION=SE /DROP=nurse_note /MAP /REPLACE.
SAVE TRANSLATE OUTFILE='stock.dbf' /TYPE=DB4 /REPLACE.
SAVE TRANSLATE OUTFILE='stock.xpt' /TYPE=SAS /VERSION=X /REPLACE.

statscraft help SAVE TRANSLATE prints the same text in the terminal. All commands

Statscraft 0.61.0, release v0.61.0

SAVE CODEPAGE

Write the active dataset to a data file whose text is in a code page.

Syntax

SAVE CODEPAGE OUTFILE='path' | handle [/ENCODING=LOCALE | 'encoding'] [/UNSELECTED=RETAIN | DELETE]
     [/KEEP=varlist] [/DROP=varlist] [/PASSPROTECT PASSWORD=NONE].

The file is a data file like the one SAVE writes, but every piece of text in it (variable names and labels, value labels, string values, the file label and the notes) is in the code page that ENCODING names, for programs that do not read data files in UTF-8. A code page is a number such as ‘1252’, or a name such as ‘windows-1257’, ‘iso-8859-1’ or ‘cp1252’; LOCALE, the default, is the legacy code page of the system. The file says which code page it is in. If any text has a character the code page lacks, nothing is written and the command stops with an error that names the text. The active dataset stays as it is, in UTF-8. UNSELECTED=DELETE leaves out the cases FILTER leaves out. KEEP and DROP shape the file only; the variables come in the order KEEP lists them. A file named .zsav gets zlib blocks and any other the case by case form. PASSPROTECT takes only PASSWORD=NONE: Statscraft does not encrypt files.

Example

SAVE CODEPAGE OUTFILE='orders_latin.sav' /ENCODING='1252' /DROP=internal_note.

statscraft help SAVE CODEPAGE prints the same text in the terminal. All commands

Statscraft 0.61.0, release v0.61.0

EXPORT

Write the active dataset to a portable (.por) file.

Syntax

EXPORT OUTFILE='path' | handle [/TYPE=COMM | TAPE] [/UNSELECTED=RETAIN | DELETE]
       [/KEEP=varlist] [/DROP=varlist] [/RENAME=(old = new) ...] [/MAP] [/DIGITS=n].

KEEP, DROP and RENAME shape the file only, in the order written; KEEP sets the order of the variables. Each MAP shows the variables as the subcommands before it leave them.

UNSELECTED=DELETE leaves out the cases FILTER leaves out. DIGITS rounds values that are not whole to n significant digits; without it every value is written exactly.

The file holds names (upper case, at most 8 bytes: longer ones are shortened and made unique, as MYLONGRO and MYLONG_2), variable and value labels, missing values, formats, the weight variable and documents. Strings hold at most 255 bytes.

Text goes in by the file’s character table: the letters, digits and marks of ASCII, and the symbols plus-minus, degree, superscript digits, less-or-equal, greater-or-equal, not-equal, dagger, dashes, cent, bullet and a few more. A character the table has no code for, such as a letter with an accent, is written as ? and a warning counts them (texts that differ only in such characters become equal), so every program that reads the file reads the same text. Control characters are written as 0; TYPE is accepted and changes nothing.

Example

EXPORT OUTFILE='wave2.por' /RENAME=(v1 TO v3 = id sex age) /MAP.

statscraft help EXPORT prints the same text in the terminal. All commands

Statscraft 0.61.0, release v0.61.0

XSAVE

Write the cases to a data file as the next data pass reads them.

Syntax

XSAVE OUTFILE='path' | handle [/KEEP=varlist] [/DROP=varlist] [/RENAME=(old = new) ...]
      [/MAP] [/COMPRESSED | /UNCOMPRESSED | /ZCOMPRESSED] [/PERMISSIONS=READONLY | WRITEABLE].

A transformation: the file holds the cases as they reach XSAVE in the next procedure or EXECUTE (or the end of the run), with the variables of that moment, scratch variables left out. KEEP, DROP and RENAME as on SAVE. MAP lists the saved variables. Two XSAVE commands cannot write the same file in one pass. Compression as on SAVE.

Example

XSAVE OUTFILE='wave2.sav' /DROP=tmp1 TO tmp5.

statscraft help XSAVE prints the same text in the terminal. All commands

Statscraft 0.61.0, release v0.61.0

NEW FILE

Start a new, empty active dataset.

Syntax

NEW FILE.

A named active dataset stays open under its name; an unnamed one is gone.

Example

NEW FILE.

statscraft help NEW FILE prints the same text in the terminal. All commands

Statscraft 0.61.0, release v0.61.0

ADD CASE

A Statscraft extension: one blank case after the last case of the active dataset.

Syntax

ADD CASE.

Not a command of the language: Statscraft adds it so that a value typed under the last case in the window’s Data tab has a case to go to. The new case is system-missing in every numeric variable and blank in every string; the transformations waiting for the data run first. A value goes in with IF ($CASENUM = n), as an edit of any other cell does.

Example

ADD CASE.
IF ($CASENUM = 4) height = 172.

statscraft help ADD CASE prints the same text in the terminal. All commands

Statscraft 0.61.0, release v0.61.0

ADD FILES

Append the cases of several data files, matching variables by name.

Syntax

ADD FILES /FILE=* | 'path' | dataset [/RENAME=(old = new) ...] [/IN=var]
          /FILE=... [/RENAME=...] [/IN=var] [/BY varlist] [/FIRST=var] [/LAST=var]
          [/MAP] [/KEEP=varlist] [/DROP=varlist].

FILE=* is the active dataset; a dataset name (DATASET NAME), quoted or not, is that open dataset and comes before a file of the same name. A variable missing from a file is blank in its cases.

The first file that has a variable gives its format and measurement level; a later file fills in a label, value labels or missing values the earlier ones lack. A string variable takes its widest width; a variable that is numeric in one file and a string in another is an error. BY interleaves files sorted by the key variables.

RENAME and IN follow their FILE; BY, FIRST, LAST, MAP, KEEP and DROP follow every FILE.

IN adds a variable that is 1 for the cases from that file, else 0. FIRST and LAST (with BY) add one that is 1 for the first or the last case of each key. These are F1.0 and go at the end, IN first; KEEP and DROP cannot name them. MAP lists the variables of the result at that point with their names in each file.

The result has the documents of every file. It stays weighted only when every file is weighted by the same variable; otherwise a warning says so.

Example

ADD FILES /FILE=* /FILE='wave2.sav' /RENAME=(q1_new = q1) /DROP=tmp.

statscraft help ADD FILES prints the same text in the terminal. All commands

Statscraft 0.61.0, release v0.61.0

MATCH FILES

Combine the variables of several data files case by case or by key.

Syntax

MATCH FILES /FILE=* | 'path' | dataset [/RENAME=(old = new) ...] [/IN=var]
            [/TABLE='path' | dataset | * [/RENAME=...] [/IN=var] ...]
            /FILE=... [/BY varlist] [/FIRST=var] [/LAST=var]
            [/MAP] [/KEEP=varlist] [/DROP=varlist].

A dataset name (DATASET NAME), quoted or not, is that open dataset and comes before a file of the same name.

With BY, cases with equal keys are joined; every file must be sorted by the keys (use SORT CASES). Without BY the n-th cases of the files are joined. A TABLE adds its variables to the cases whose key it holds and adds no cases; it may hold each key once. A variable in several files takes its value from the first file that has the case.

RENAME and IN follow their FILE or TABLE; BY, FIRST, LAST, MAP, KEEP and DROP follow every FILE and TABLE. IN (with BY) adds a variable that is 1 for the cases that file or table has, else 0. FIRST and LAST (with BY) add one that is 1 for the first or the last case of each key. These are F1.0 and go at the end, IN first; KEEP and DROP cannot name them. MAP lists the variables of the result at that point with their names in each file.

The result has the documents of every file and keeps the weight when every weighted file uses the same variable and KEEP or DROP leave it; otherwise a warning says so.

Example

MATCH FILES /FILE=* /TABLE='regions.sav' /BY region.

statscraft help MATCH FILES prints the same text in the terminal. All commands

Statscraft 0.61.0, release v0.61.0

STAR JOIN

Add the fields of lookup files to every case of a data file, by keys, as an SQL left join.

Syntax

STAR JOIN /SELECT * | alias.field [AS name], alias.field [AS name], ...
          /FROM 'path' [PASSWORD='text'] | dataset | * AS alias
          /JOIN 'path' [PASSWORD='text'] | dataset | * AS alias
                ON alias.key = alias.key [AND alias.key = alias.key ...] [IN=name]
          [/JOIN ...] /OUTFILE FILE='path' | dataset | *
          [/PASSPROTECT PASSWORD='text' | NONE [ENCRYPTEDPW=NO | YES]].

The subcommands come in this order and every keyword is written in full. A dataset name, quoted or not, is that open dataset and comes before a file of the same name.

Every case of FROM is kept, in its order; a JOIN adds its fields to the cases whose keys it holds and leaves them blank (system-missing, empty) elsewhere. The files need no sorting, and each JOIN has its own keys. ON pairs a field of FROM with one of that JOIN, numeric with numeric, string with string (widths may differ; trailing blanks do not count). The keys of a JOIN must be unique there. A system-missing key matches nothing.

IN=name adds a variable that is 1 where the JOIN had the case and 0 where not.

The result holds the SELECT fields and every key: SELECT * is every field of every source, and a JOIN key of the same name as its FROM key appears once, from FROM. Keys not named on SELECT come first; the rest follow in SELECT order; IN variables last.

A name that two sources bring gets its alias in front (t1.name, t2.name) unless AS names it. The dictionary comes from FROM (with its weight, filter and split); a key without labels or missing values takes them from the first JOIN that has them; the documents of every file are kept; the file label is dropped. Not after TEMPORARY.

OUTFILE=* replaces the active dataset, a dataset name (DATASET DECLARE) fills that dataset, a path writes a data file. PASSWORD on FROM and JOIN is accepted for files that are not encrypted (encrypted ones cannot be read); PASSPROTECT with a password is refused for a file, since Statscraft writes no encrypted files, and ignored otherwise.

Example

STAR JOIN /SELECT t1.id, t1.region, t2.name /FROM * AS t1
  /JOIN 'regions.sav' AS t2 ON t1.region = t2.region /OUTFILE FILE=*.

statscraft help STAR JOIN prints the same text in the terminal. All commands

Statscraft 0.61.0, release v0.61.0

UPDATE

Replace values of a primary file with the values of transaction files, by key.

Syntax

UPDATE FILE=* | 'path' | dataset [/RENAME=(old = new) ...] [/IN=var]
       /FILE=... [/RENAME=...] [/IN=var] [/FILE=...] /BY varlist
       [/MAP] [/KEEP=varlist] [/DROP=varlist].

The first FILE is the primary file, which may hold each key once; the others are transactions. Every file must be sorted by the keys. A transaction value replaces the value of the case with its key unless it is system-missing, user-missing or blank; transactions apply in order, case by case and file by file. A key only a transaction has adds a case, a variable only a transaction has adds a variable. Dictionaries combine as in MATCH FILES.

IN adds a variable at the end, 1 for the cases that file holds, else 0 (F1.0); KEEP and DROP cannot name it. MAP lists the variables at that point with their names in each file.

There is no FIRST or LAST, since every key gives one case. The weight and the documents follow MATCH FILES. FILE=* cannot follow TEMPORARY.

Example

UPDATE FILE='customers.sav' /FILE='changes.sav' /IN=changed /BY id.

statscraft help UPDATE prints the same text in the terminal. All commands

Statscraft 0.61.0, release v0.61.0

COMPARE DATASETS

Compare the values and dictionary of the active dataset with another dataset or .sav file.

Syntax

COMPARE DATASETS /COMPDATASET 'file.sav' [PASSWORD='text'] | dataset
  /VARIABLES varlist | ALL [/CASEID varlist]
  [/SAVE [FLAGMISMATCHES=YES | NO] [VARNAME=name]
         [MATCHDATASET=NO | YES] [MATCHNAME=dataset | 'file' [MATCHPASS='text' | NONE]]
         [MISMATCHDATASET=NO | YES] [MISMATCHNAME=dataset | 'file' [MISMATCHPASS=...]]
         [ENCRYPTEDPW=NO | YES]]
  [/OUTPUT [VARPROPERTIES=NONE | ALL | MEASURE LABEL VALUELABELS COLUMNS MISSING ALIGN ROLE
                          ATTRIBUTES WIDTH] [CASETABLE=YES | NO [TABLELIMIT=100 | n | NONE]]].

Every subcommand and keyword is written in full. Without CASEID the first case of each file is paired with the first of the other, and so on; with CASEID cases pair by their key values and both files must be sorted by the keys in ascending order (a key held twice pairs in file order).

Each listed variable that the other file also has, with the same type, is compared value by value: numbers exactly, system-missing equal only to system-missing, strings without trailing blanks. A variable the other file lacks or holds with the other type is listed, not compared.

The tables: a summary of cases and variables, the variables not compared, the number of cases that differ per variable, and the case table (one row per differing value, the first 100 cases by default). The flag variable, CasesCompare unless VARNAME names another, is added to the active dataset unless FLAGMISMATCHES=NO: 0 the paired case has the same values, 1 it differs, -1 the other file has no such case; an existing numeric variable of that name is overwritten. MATCHDATASET and MISMATCHDATASET write the active cases flagged 0, or flagged 1 or -1, to a dataset declared before or a .sav file; encrypted files cannot be written.

VARPROPERTIES lists every requested property that differs between the files. SPLIT FILE and FILTER are ignored.

Example

COMPARE DATASETS /COMPDATASET 'wave1_checked.sav' /VARIABLES q1 TO q12 /CASEID respid
  /SAVE VARNAME=changed MISMATCHDATASET=YES MISMATCHNAME=review
  /OUTPUT VARPROPERTIES=LABEL VALUELABELS TABLELIMIT=50.

statscraft help COMPARE DATASETS prints the same text in the terminal. All commands

Statscraft 0.61.0, release v0.61.0

VARIABLE LABELS

Set the labels of variables.

Syntax

VARIABLE LABELS var 'label' [[/] var 'label' ...].

A label replaces the variable’s earlier one and is shown in place of the name in the output. An empty label (‘’) clears it. Scratch variables (names that start with #) take no label.

Example

VARIABLE LABELS spend 'Monthly bill in euros' / age_group 'Age band'.

statscraft help VARIABLE LABELS prints the same text in the terminal. All commands

Statscraft 0.61.0, release v0.61.0

VALUE LABELS

Replace the value labels of variables.

Syntax

VALUE LABELS varlist value 'label' [value 'label' ...] [/ varlist ...].

Values are numbers or quoted strings. A varlist with no labels removes its labels.

Example

VALUE LABELS gender 1 'Male' 2 'Female' / plan 'b' 'Basic' 'p' 'Premium'.

statscraft help VALUE LABELS prints the same text in the terminal. All commands

Statscraft 0.61.0, release v0.61.0

MISSING VALUES

Declare user-missing values.

Syntax

MISSING VALUES varlist (values) [[/] varlist (values) ...].

values: up to three values, or one range with at most one extra value.

range: low THRU high, LOWEST THRU high, low THRU HIGHEST (LO and HI also work).

Empty parentheses clear the missing values.

Example

MISSING VALUES q1 q2 (98, 99) / income (LOWEST THRU -1, 999999) / plan ().

statscraft help MISSING VALUES prints the same text in the terminal. All commands

Statscraft 0.61.0, release v0.61.0

VARIABLE LEVEL

Set the measurement level of variables.

Syntax

VARIABLE LEVEL varlist (SCALE | ORDINAL | NOMINAL) [[/] varlist (...) ...].

Example

VARIABLE LEVEL age (SCALE) / q1 TO q5 (ORDINAL).

statscraft help VARIABLE LEVEL prints the same text in the terminal. All commands

Statscraft 0.61.0, release v0.61.0

VARIABLE WIDTH

Set how many characters wide variables show in the data grid.

Syntax

VARIABLE WIDTH varlist (n) [[/] varlist (n) ...].

n: a whole number of characters, at least 1. Saved with the data; formats and output stay as they are.

Example

VARIABLE WIDTH comment (40) / id age (5).

statscraft help VARIABLE WIDTH prints the same text in the terminal. All commands

Statscraft 0.61.0, release v0.61.0

FORMATS

Set the display format of variables.

Syntax

FORMATS varlist (format) [[/] varlist (format) ...].

format: type, width and optional decimals, for example F8.2, A20, DATE11.

Output shows values in the format: DATE11 28-OCT-1990, DATE9 28-OCT-90, ADATE10 10/28/1990, TIME8 01:02:34, TIME5 01:02 (what the width cannot show is cut off), CCA to CCE as SET defines.

Procedures show the mean, median, mode, minimum, maximum and percentiles of a date, time or custom currency variable in its format; a spread of dates as days and time (DTIME).

Example

FORMATS income (COMMA10.2) / age (F3).

statscraft help FORMATS prints the same text in the terminal. All commands

Statscraft 0.61.0, release v0.61.0

PRINT FORMATS

Set the print format of variables: how procedures and PRINT show them.

Syntax

PRINT FORMATS varlist (format) [[/] varlist (format) ...].

As FORMATS, but the write format stays as it is. A string variable keeps its width.

Example

PRINT FORMATS salary (DOLLAR8) / rate (PCT5.1).

statscraft help PRINT FORMATS prints the same text in the terminal. All commands

Statscraft 0.61.0, release v0.61.0

WRITE FORMATS

Set the write format of variables: how WRITE writes them.

Syntax

WRITE FORMATS varlist (format) [[/] varlist (format) ...].

As FORMATS, but the print format stays as it is. Saved with the data file.

Example

WRITE FORMATS salary (F10.2).

statscraft help WRITE FORMATS prints the same text in the terminal. All commands

Statscraft 0.61.0, release v0.61.0

RENAME VARIABLES

Change the names of variables.

Syntax

RENAME VARIABLES (oldlist = newlist) [(oldlist = newlist) ...].
RENAME VARIABLES old = new [old = new ...].

All renames happen at once, so (a b = b a) swaps two names. new1 TO new3 counts up.

Example

RENAME VARIABLES (q1 q2 = satisfaction recommend) (v1 TO v3 = item1 TO item3).

statscraft help RENAME VARIABLES prints the same text in the terminal. All commands

Statscraft 0.61.0, release v0.61.0

DELETE VARIABLES

Remove variables from the dataset.

Syntax

DELETE VARIABLES varlist.

The command removes the variables and their values from the active dataset at once. At least one variable must remain. Deleting the weight variable turns weighting off.

Example

DELETE VARIABLES ch_web TO ch_email.

statscraft help DELETE VARIABLES prints the same text in the terminal. All commands

Statscraft 0.61.0, release v0.61.0

SORT CASES

Sort the cases by the values of variables.

Syntax

SORT CASES [BY] varlist [(A | D)] [varlist [(A | D)] ...].

A is ascending (the default), D descending; a direction covers the variables before it.

System-missing sorts lowest. Cases with equal keys keep their order.

Example

GET FILE='survey.sav'.
SORT CASES BY spend (D).
LIST id region spend /CASES=FROM 1 TO 5.
SORT CASES BY region age_group (A) age (D).

The example reads the sample data file survey.sav, an invented customer survey; save it in the folder you run the syntax from.

Example output

List

idregionspend
1294.52
113290.56
80385.18
49379.74
61272.36

statscraft help SORT CASES prints the same text in the terminal. All commands

Statscraft 0.61.0, release v0.61.0

SORT VARIABLES

Put the variables in order by a property of their dictionary entries.

Syntax

SORT VARIABLES [BY] NAME | TYPE | FORMAT | LABEL | VALUES | MISSING | MEASURE | ROLE | COLUMNS
               | ALIGNMENT | ATTRIBUTE name [(A | D)].

A or UP is ascending (the default), D or DOWN reverses the whole order.

NAME: letters without regard to case, then a number at the end by its value (v2 before v10).

TYPE: numeric, then strings from narrow to wide. FORMAT: by format type in the order of the data file codes (A, COMMA, DOLLAR, F, … DATE …), then width and decimals.

LABEL, VALUES, MISSING, ATTRIBUTE: variables without one come first; then labels and attribute values without regard to case; value labels and missing values so that equal definitions sit together. MEASURE: nominal, ordinal, scale. ROLE: input, target, both, none, partition, split. COLUMNS: display width (default 8 for numbers, the width for strings).

ALIGNMENT: left, right, center. Variables that tie keep their order.

Example

SORT VARIABLES BY NAME (A).

statscraft help SORT VARIABLES prints the same text in the terminal. All commands

Statscraft 0.61.0, release v0.61.0

SHIFT VALUES

New variables that hold the value of the same variable in an earlier or later case.

Syntax

SHIFT VALUES VARIABLE=var RESULT=newvar {LEAD=n | LAG=n | SHIFT=n}
             [/VARIABLE=var RESULT=newvar {LEAD=n | LAG=n | SHIFT=n}] ...

LEAD=n takes the value from the case n after the current one, LAG=n from n before it, and SHIFT=n from n after it, or from -n before it when n is negative. n is a whole number and 0 copies the value in place. The result must be a name no variable has yet. The first or last n cases of the data (of each split group) get the system-missing value, or an empty string.

The result is of the same type as the variable and keeps its format, value labels, missing values and measurement level, but not its custom attributes; its label tells what shifted it. User-missing values are carried over as they are. A filter is ignored: every case counts.

Example

SHIFT VALUES VARIABLE=price RESULT=price_next LEAD=1 /VARIABLE=price RESULT=price_prev LAG=1.

statscraft help SHIFT VALUES prints the same text in the terminal. All commands

Statscraft 0.61.0, release v0.61.0

WEIGHT

Weight the cases by a variable, or turn weighting off.

Syntax

WEIGHT BY var.
WEIGHT OFF.

The command makes each case count as many times as its value of var, a numeric variable: a case with weight 2.5 counts as two and a half cases. Weighting stays on until WEIGHT OFF, until the variable is deleted, or until another data file is read, and SAVE stores it with the data. Fractional weights are used as they are in counts, percentages and statistics; most significance tests, confidence intervals and standard errors round them. A case whose weight is zero, negative or missing is left out. SHOW WEIGHT tells which variable weights the data.

Example

GET FILE='survey.sav'.
WEIGHT BY weight.
FREQUENCIES age_group.
WEIGHT OFF.
FREQUENCIES age_group.

The example reads the sample data file survey.sav, an invented customer survey; save it in the folder you run the syntax from.

Example output

Age group

CategoryValueLabelFrequencyPercentValid PercentCumulative Percent
valid118-2950.6815.9715.9715.97
valid230-44106.5133.5533.5549.52
valid345-59117.8237.1237.1286.64
valid460 and over42.4113.3613.36100
total317.42100

statscraft help WEIGHT prints the same text in the terminal. All commands

Statscraft 0.61.0, release v0.61.0

AGGREGATE

Aggregate groups of cases into new variables or a new dataset.

Syntax

AGGREGATE [/OUTFILE=* | 'path' | dataset [MODE=ADDVARIABLES | REPLACE]] [/MISSING=COLUMNWISE] [/PRESORTED]
          [/BREAK=varlist [(A | D)] ...]
          /target ['label'] [target ...] = function(varlist) [/target ...].

OUTFILE=* replaces the active dataset with one case per break group (break variables, then targets); with MODE=ADDVARIABLES it keeps the cases and adds the targets to each of them.

OUTFILE=‘path’ writes the aggregated dataset to a file and leaves the active dataset alone; OUTFILE=dataset puts it into a dataset that DATASET DECLARE or DATASET NAME defined.

Without OUTFILE the targets are added to every case, as with OUTFILE=* MODE=ADDVARIABLES.

functions: SUM MEAN SD MEDIAN MIN MAX FIRST LAST N NU NMISS NUMISS; N and NU also without (varlist).

PGT PLT FGT FLT CGT CLT (varlist, value) and PIN POUT FIN FOUT CIN COUT (varlist, low, high): the percentage, fraction or count of the valid values above, below, inside (bounds included) or outside (bounds excluded); bounds the wrong way round are swapped, strings compare as text.

Missing values are skipped; a period after the function name (SUM.(x), PGT.(x, 30), N.(x)) counts user-missing values as valid, so NMISS.(x) and NUMISS.(x) count the system-missing ones alone; FIRST., LAST., MIN. and MAX. may pick a user-missing value, which keeps its status in the target. On N or NU without a variable the period changes nothing, and a period that ends the line ends the command. A weight variable’s own user-missing values still weigh nothing.

With MISSING=COLUMNWISE a group with one missing value gets a missing result (N, NU, NMISS and NUMISS still count). PRESORTED keeps the cases in file order and makes a group of each run of adjacent cases with the same break values. With a weight variable SUM, MEAN, SD, MEDIAN, N and NMISS are weighted.

Example

GET FILE='survey.sav'.
AGGREGATE /OUTFILE=* MODE=ADDVARIABLES /BREAK=region
  /region_spend = MEAN(spend) /region_n = N.
COMPUTE above_region = spend > region_spend.
GET FILE='survey.sav'.
AGGREGATE /OUTFILE=* /BREAK=region
  /respondents = N /mean_spend = MEAN(spend) /share_recommend = MEAN(recommend).
LIST.

The example reads the sample data file survey.sav, an invented customer survey; save it in the folder you run the syntax from.

Example output

List

regionrespondentsmean_spendshare_recommend
17536.14.73
26240.50.63
38138.47.54
48239.19.60

statscraft help AGGREGATE prints the same text in the terminal. All commands

Statscraft 0.61.0, release v0.61.0

VARSTOCASES

Turn groups of variables into cases: one new case per variable of the group.

Syntax

VARSTOCASES /MAKE new ['label'] [FROM] varlist [/MAKE ...]
            [/INDEX=i ['label'] | i ['label'] (make) | i ['label'] (n) j ['label'] (n) ...]
            [/ID=new ['label']] [/NULL=DROP | KEEP] [/COUNT=new ['label']]
            [/KEEP=ALL | varlist | /DROP=varlist].

Every case becomes one case per variable of the FROM lists, in their order; FROM lists have equal lengths and one type each. A MAKE variable takes the dictionary of its first FROM variable (strings their widest width), the label given replacing the label. The other variables are copied to every new case (KEEP: only those, in that order). INDEX numbers the new cases 1, 2, …; with (make) it holds the names of that MAKE’s FROM variables; with (n) several factors whose levels multiply to the length of the lists, the last varying fastest.

ID is the case number of the original case (F8.0), COUNT the number of new cases it gave (F4.0). NULL=DROP (the default) leaves out a new case whose MAKE values are all system-missing or blank. Order of the new file: ID, the copied variables, COUNT, INDEX, MAKE; ID and INDEX are nominal, COUNT scale. All cases are used whatever FILTER says; WEIGHT, SPLIT FILE and FILTER stay unless their variables are gone. Not after TEMPORARY.

Example

VARSTOCASES /MAKE score 'Score' FROM score1 TO score4 /INDEX=wave /ID=person.

statscraft help VARSTOCASES prints the same text in the terminal. All commands

Statscraft 0.61.0, release v0.61.0

CASESTOVARS

Turn groups of cases into one case each, with a variable per value of an index.

Syntax

CASESTOVARS [/ID=varlist] [/INDEX=varlist] [/FIXED=varlist] [/AUTOFIX=YES | NO]
            [/VIND [ROOT=name]] [/COUNT=new ['label']] [/RENAME var=root ...]
            [/SEPARATOR='text'] [/GROUPBY=VARIABLE | INDEX] [/DROP=varlist].

A row group is a run of cases with the same values of the split and ID variables; the data must be sorted by them. Cases with a system-missing or blank ID are left out with a warning. Every other variable that varies within a group becomes a variable group: one variable per index value (INDEX: the values or combinations that occur, ascending; without INDEX the position in the group), named root, separator (‘.’) and the index values. With one string index the values are the names (root, separator and value when several variables are restructured); names that cannot be used become V1, V2, … AUTOFIX=YES copies variables that do not vary (one value plus system-missing or blanks counts as not varying), and warns about FIXED variables that vary; AUTOFIX=NO makes such a FIXED variable an error. New variables keep the dictionary of their source; the label adds the index values. VIND adds a 0/1 indicator (F1.0) per index value, COUNT the cases of the group (F4.0). Order: split, ID and fixed variables as in the file, the variable groups, the indicators, COUNT. User-missing values count as values. All cases are used whatever FILTER says; WEIGHT, SPLIT FILE and FILTER stay unless their variables are gone or spread. Not after TEMPORARY.

Example

CASESTOVARS /ID=person /INDEX=wave /GROUPBY=VARIABLE.

statscraft help CASESTOVARS prints the same text in the terminal. All commands

Statscraft 0.61.0, release v0.61.0

FLIP

Transpose the data: variables become cases and cases become variables.

Syntax

FLIP [VARIABLES=ALL | varlist] [/NEWNAMES=var].

Each variable becomes a case, named in the new string variable CASE_LBL; each case becomes a numeric variable (F8.2), named VAR001, VAR002, … or by the values of NEWNAMES (the values of CASE_LBL after an earlier FLIP). Names are upper case; a number gets K_ in front, as does a name that does not start with a letter; other characters a name cannot hold become _, and a repeated name gets _A, _B, …; a missing or blank value keeps the default name. String values and user-missing values become system-missing. Every case is transposed whatever FILTER says. Labels, value labels, the weight, the split and the filter are gone.

Transformations before FLIP become permanent: TEMPORARY ends. A table lists the new names.

Example

FLIP VARIABLES=income price year /NEWNAMES=country.

statscraft help FLIP prints the same text in the terminal. All commands

Statscraft 0.61.0, release v0.61.0

ADD VALUE LABELS

Add or change value labels, keeping the other labels of the variables.

Syntax

ADD VALUE LABELS varlist value 'label' [value 'label' ...] [/ varlist ...].

Values are numbers or quoted strings; a label may be joined from pieces with +.

Example

ADD VALUE LABELS q1 TO q5 9 'No answer' / plan 'x' 'Unknown'.

statscraft help ADD VALUE LABELS prints the same text in the terminal. All commands

Statscraft 0.61.0, release v0.61.0

FILE LABEL

Set the label of the data file.

Syntax

FILE LABEL text.

The text needs no quotes; a label that starts with a quote is read as a quoted string.

Example

FILE LABEL Survey wave 2, cleaned.

statscraft help FILE LABEL prints the same text in the terminal. All commands

Statscraft 0.61.0, release v0.61.0

DOCUMENT

Add free text to the documents of the data file.

Syntax

DOCUMENT text.

The text may run over several lines and hold blank lines; a line ending in a period ends it. Every line becomes a line of the documents.

Example

DOCUMENT Weights were trimmed at 5.

statscraft help DOCUMENT prints the same text in the terminal. All commands

Statscraft 0.61.0, release v0.61.0

ADD DOCUMENT

Add quoted lines to the documents of the data file.

Syntax

ADD DOCUMENT 'line' ['line' ...].

Each string is one line; an empty string gives a blank line.

Example

ADD DOCUMENT 'Cleaned on 10 November.' 'Outliers removed.'

statscraft help ADD DOCUMENT prints the same text in the terminal. All commands

Statscraft 0.61.0, release v0.61.0

DROP DOCUMENTS

Remove the documents of the data file.

Syntax

DROP DOCUMENTS.

The command removes every document line that DOCUMENT or ADD DOCUMENT stored with the data. The change is saved with the next SAVE.

Example

DROP DOCUMENTS.

statscraft help DROP DOCUMENTS prints the same text in the terminal. All commands

Statscraft 0.61.0, release v0.61.0

VARIABLE ROLE

Set the role of variables for dialogs.

Syntax

VARIABLE ROLE /INPUT varlist /TARGET varlist /BOTH varlist /NONE varlist
              /PARTITION varlist /SPLIT varlist.

At least one subcommand; a variable named twice keeps its last role.

Example

VARIABLE ROLE /INPUT age income /TARGET satisfaction /NONE id.

statscraft help VARIABLE ROLE prints the same text in the terminal. All commands

Statscraft 0.61.0, release v0.61.0

VARIABLE ALIGNMENT

Set the alignment of variables in the data grid.

Syntax

VARIABLE ALIGNMENT varlist (LEFT | RIGHT | CENTER) [[/] varlist (...) ...].

Example

VARIABLE ALIGNMENT id (LEFT) / q1 TO q5 (CENTER).

statscraft help VARIABLE ALIGNMENT prints the same text in the terminal. All commands

Statscraft 0.61.0, release v0.61.0

VARIABLE ATTRIBUTE

Set or delete custom attributes of variables.

Syntax

VARIABLE ATTRIBUTE VARIABLES=varlist ATTRIBUTE=name('value') [name[n]('value') ...]
                   [DELETE=name [name[n] ...]] [/VARIABLES=...].

name[n] is element n of an attribute array (from 1); DELETE=name[n] removes it and moves the later elements up, DELETE=name removes the whole attribute. Values are always quoted.

Example

VARIABLE ATTRIBUTE VARIABLES=q1 q2 ATTRIBUTE=Source('wave 2') Note[2]('checked').

statscraft help VARIABLE ATTRIBUTE prints the same text in the terminal. All commands

Statscraft 0.61.0, release v0.61.0

DATAFILE ATTRIBUTE

Set or delete custom attributes of the data file.

Syntax

DATAFILE ATTRIBUTE ATTRIBUTE=name('value') [name[n]('value') ...] [DELETE=name ...].

As VARIABLE ATTRIBUTE, for the file.

Example

DATAFILE ATTRIBUTE ATTRIBUTE=Version('2') Revised[1]('2026-11-10').

statscraft help DATAFILE ATTRIBUTE prints the same text in the terminal. All commands

Statscraft 0.61.0, release v0.61.0

ALTER TYPE

Change the type, string width or format of variables.

Syntax

ALTER TYPE varlist ([input =] format | AMIN [+ n[%]]) [varlist (...) ...] [/PRINT ...].

A string variable may get another width (A20); values longer than it are cut. A numeric variable may get another numeric format, or become a string holding its formatted values; a string may become numeric with an F, COMMA, DOT, E, DOLLAR, PCT or N format, or a date or time with a DATE, ADATE, EDATE, SDATE, JDATE, QYR, MOYR, WKYR, DATETIME, YMDHMS, TIME or MTIME format (ALTER TYPE visit (A12 = ADATE12)), read in the width of the format as DATA LIST reads it; a value that does not fit the format becomes system-missing. A type change drops value labels and missing values.

input = (A=, F=, A10=) limits the change to variables of that type and width.

AMIN gives a string variable the width of its longest value, plus n bytes or n percent of that width (rounded).

/PRINT=ALTEREDTYPES (the default) lists the variables whose format changed, with the old and the new format; ALTEREDVALUES lists the values that changed with the type or the width (every value when the type changed, the cut ones when only the width did), the first 25 of each variable, by case number; NONE shows no report and does not go with the others.

Example

ALTER TYPE comment (A500) code (A=AMIN).

statscraft help ALTER TYPE prints the same text in the terminal. All commands

Statscraft 0.61.0, release v0.61.0

APPLY DICTIONARY

Copy dictionary information from a data file or dataset to the active dataset.

Syntax

APPLY DICTIONARY FROM 'file' | dataset | * [/SOURCE VARIABLES=varlist]
                 [/TARGET VARIABLES=varlist] [/NEWVARS]
                 [/FILEINFO [ATTRIBUTES[=REPLACE | MERGE]] [DOCUMENTS[=...]] [FILELABEL]
                            [MRSETS[=...]] [VARSETS[=...]] [WEIGHT] [ALL]]
                 [/VARINFO [ALIGNMENT] [ATTRIBUTES[=...]] [FORMATS] [LEVEL] [MISSING]
                           [ROLE] [VALLABELS[=REPLACE | MERGE]] [VARLABEL] [WIDTH] [ALL]].

Variables match by name and type; with a different type only the label is copied.

Without VARINFO everything but attributes is copied, value labels replacing; without FILEINFO only the weight. SOURCE with one variable and TARGET copies that variable’s information to every target of the same type. Empty information in the source does not overwrite the active dataset’s. NEWVARS adds the source variables the active dataset lacks, with their dictionary information and missing values; without an active dataset it makes one with the source’s variables and no cases.

Example

APPLY DICTIONARY FROM 'template.sav' /FILEINFO VARSETS=MERGE MRSETS.

statscraft help APPLY DICTIONARY prints the same text in the terminal. All commands

Statscraft 0.61.0, release v0.61.0

DATA LIST

Define text data, inline or in a file, and read it as the new active dataset.

Syntax

DATA LIST [FILE='path'] [ENCODING='name'] [FIXED | FREE [(delimiters)] | LIST [(delimiters)]]
          [RECORDS=n] [SKIP=n] [END=var] /[record] var [TO var] columns [(type[,decimals])] | (formats) [/ ...].

FIXED (the default): columns such as 1-3, or formats such as (F2.0, 1X, A10) with Tn and nX.

FREE and LIST: var [(format)], values separated by blanks and commas or by the delimiters given as quoted characters or TAB; LIST reads one case per line. * ends a run of F8.2 variables.

Without FILE the data follow between BEGIN DATA and END DATA; transformations may stand between. Inside INPUT PROGRAM each run reads the next case’s records into the case being built; without variables it passes over a record. END (fixed data in an input program only) names a variable that is 0, and 1 once the data are used up.

Formats: F, N, E, COMMA, DOT, DOLLAR, PCT, Z (zoned decimal: 1234A is 12341, 1234J is -12341), PIBHEX (hexadecimal digits, the whole width), A, DATE, ADATE, EDATE, SDATE, JDATE (yyddd or yyyyddd), QYR (4Q90, Q4 1990), MOYR (Oct-1990), WKYR (43WK90, 43 1990), DATETIME, YMDHMS (year first), TIME (hours:minutes:seconds), MTIME (minutes:seconds), DTIME (days, then time). A date may be written with blanks, dashes, slashes, periods or commas between its parts, a month as a number, a Roman numeral or a name, or with no delimiter at all (28OCT1990, 10281990); a two-digit year falls in the 100 years from SET EPOCH; a time with no colons is hhmm or hhmmss.

ENCODING is how the text of FILE is encoded: UTF8 (the default, or the encoding a FILE HANDLE gives), a code page such as ‘1257’ or ‘windows-1252’, UTF16LE, UTF16BE (ignored without FILE). Fixed columns and the widths of A formats count bytes in a UTF-8 file (a letter with an accent takes two); columns count letters in a code page or UTF-16 file, but the width of a string is still in bytes of UTF-8.

A value that cannot be read is system-missing, with a warning naming its line.

Example

DATA LIST LIST /id (F3) name (A12) score.

statscraft help DATA LIST prints the same text in the terminal. All commands

Statscraft 0.61.0, release v0.61.0

KEYED DATA LIST

Read variables from the record of a text file that a key variable picks, for each case.

Syntax

KEYED DATA LIST FILE=handle | 'path' KEY=var IN=var [TABLE | NOTABLE] [ENCODING='encoding']
    /var columns [(type[,decimals])] | (formats) ...

For every case the record that KEY names is read from the file and its variables are added to the case, as DATA LIST would read them from one line in fixed columns. A numeric KEY reads the record of that number (1 for the first line, a whole number up to the number of lines): the file is direct-access. A string KEY reads the first record that begins with the key, without its trailing blanks: the file is keyed. IN names a variable that is set to 1 when the record was read and to 0 when there is none (a key that is missing, no whole number in range, or matches no record); the variables read keep their value or stay missing then. A variable that exists is given the value of the record for the cases where one is found. The command works on the cases that are there, or inside an input program, where a run reads one record whatever the outcome. Scratch variables may serve as KEY and IN. TABLE and NOTABLE change nothing.

Example

KEYED DATA LIST FILE=courses KEY=#key IN=#found /period 13 credits 16.

statscraft help KEYED DATA LIST prints the same text in the terminal. All commands

Statscraft 0.61.0, release v0.61.0

BEGIN DATA

Inline data for the DATA LIST before it, up to a line that holds END DATA.

Syntax

BEGIN DATA

data lines END DATA.

BEGIN DATA and END DATA each stand alone on their line. Every line between is data.

Example

BEGIN DATA
1 'Ann' 12.5
END DATA.

statscraft help BEGIN DATA prints the same text in the terminal. All commands

Statscraft 0.61.0, release v0.61.0

MATRIX DATA

Read matrix materials (correlations, means, counts) as a matrix data file.

Syntax

MATRIX DATA VARIABLES=varlist [/FILE=INLINE | 'path'] [/FORMAT=[LIST | FREE] [LOWER | UPPER | FULL]
            [DIAGONAL | NODIAGONAL]] [/SPLIT=varlist] [/FACTORS=varlist] [/CELLS=n] [/N=n]
            [/CONTENTS=[CORR] [COV] [MAT] [MSE] [DFE] [MEAN] [STDDEV | SD] [N_VECTOR | N] [N_SCALAR]
            [N_MATRIX] [COUNT] [PROX] [(types of within-cells records) ...]].

The new active dataset holds the split variables (F4.0), ROWTYPE_ (A8), the factors (F4.0), VARNAME_ (A8, wider for longer names) and the continuous variables (F10.4): those of VARIABLES that are neither ROWTYPE_ nor a split or factor, which come last on VARIABLES.

With ROWTYPE_ on VARIABLES each record starts with its fields in the order of VARIABLES: the record type (a name or a three-letter abbreviation, quoted or not) and the split and factor values (. for a pooled record). Without it CONTENTS gives the records in order, CORR when left out; types in parentheses are within-cells records, read for each of the CELLS cells with the factor values first. A matrix has one record per variable: LOWER and UPPER give a triangle, which is mirrored, FULL the whole matrix; with NODIAGONAL a correlation diagonal is 1 and any other diagonal missing. N_SCALAR gives one value for every variable.

N=n adds an N record to each split. LIST starts each row on a new record (a row may go on over the next records; values left on a record are ignored with a warning), FREE reads the values as one stream. Values are separated by blanks or commas, and by + and - when not after D or E; . is missing. SPLIT may name one variable that is not on VARIABLES: the sets of materials are then numbered 1, 2, … The result is split by the split variables. The data follow between BEGIN DATA and END DATA, or come from FILE. FACTOR, CLUSTER and the other procedures with MATRIX=IN(*) read it.

Example

MATRIX DATA VARIABLES=ROWTYPE_ q1 TO q3 /FORMAT=UPPER NODIAGONAL.
BEGIN DATA
MEAN 12 7 30
SD 2 1.5 4
N 40 40 40
CORR .25 .4
CORR -.3
END DATA.

statscraft help MATRIX DATA prints the same text in the terminal. All commands

Statscraft 0.61.0, release v0.61.0

MCONVERT

Matrix data between covariances and correlations with standard deviations.

Syntax

MCONVERT [[/MATRIX=] [IN({* | file})] [OUT({* | file})]] [/REPLACE | /APPEND].

Reads matrix materials (the layout MATRIX DATA makes: split variables, ROWTYPE_, grouping variables, VARNAME_, then the variables) from the active dataset or a file and writes the other form to the active dataset (replacing it) or a file. COV records become CORR records and a STDDEV record, the square roots of the variances (not added when the set has one).

CORR records become COV records and need the set’s STDDEV record. Each run of records with the same split and grouping values is a set, converted on its own. Records of other types (MEAN, N, STDDEV …) are copied. REPLACE, the default, writes the converted matrix in place of the original; APPEND writes each original set followed by its converted matrix. The matrix of a set must have one record per variable, in the order of the variables. The original stays as it was in the file or dataset it came from, unless that is also the output.

IN and OUT cannot name the same file.

Example

MCONVERT MATRIX=IN(*) OUT(correlations) /APPEND.

statscraft help MCONVERT prints the same text in the terminal. All commands

Statscraft 0.61.0, release v0.61.0

INPUT PROGRAM

Start an input program: commands that build the cases of a new active dataset.

Syntax

INPUT PROGRAM.
  DATA LIST, REREAD, REPEATING DATA, END CASE, END FILE and transformations

END INPUT PROGRAM.

The commands run again and again, each time from the top, until a DATA LIST runs out of data or END FILE runs. Each run builds a case at its end, or at each END CASE when the program has one. Before each case the variables are blank or system-missing again, except scratch variables and those named on LEAVE. A run that reads no record and does not end the file is an error, since it would repeat forever. SELECT IF, SAMPLE, FILTER, TEMPORARY and procedures cannot stand inside. The program runs right away, or at BEGIN DATA when it reads inline data.

Example

INPUT PROGRAM.
DATA LIST /#n 1 head 3-4 (A).
LEAVE head.
LOOP #i = 1 TO #n.
DATA LIST /item 1-2.
END CASE.
END LOOP.
END INPUT PROGRAM.

statscraft help INPUT PROGRAM prints the same text in the terminal. All commands

Statscraft 0.61.0, release v0.61.0

END INPUT PROGRAM

End an input program and run it.

Syntax

END INPUT PROGRAM.

Example

INPUT PROGRAM.
LOOP #i = 1 TO 5.
COMPUTE x = #i.
END CASE.
END LOOP.
END FILE.
END INPUT PROGRAM.

statscraft help END INPUT PROGRAM prints the same text in the terminal. All commands

Statscraft 0.61.0, release v0.61.0

END CASE

In an input program: add the case built so far to the dataset and go on.

Syntax

END CASE.

The program goes on with the command after END CASE, with the variables blank or system-missing again except scratch and LEAVE variables. With END CASE in a program no case is built at the end of a run.

Example

LOOP #k = 1 TO 4.
COMPUTE score = item(#k).
END CASE.
END LOOP.

statscraft help END CASE prints the same text in the terminal. All commands

Statscraft 0.61.0, release v0.61.0

END FILE

In an input program or FILE TYPE: stop reading; the case being built is dropped.

Syntax

END FILE.

Usually inside DO IF. Put END CASE before it to keep the case being built.

Example

DO IF day > 30.
END FILE.
END IF.

statscraft help END FILE prints the same text in the terminal. All commands

Statscraft 0.61.0, release v0.61.0

REREAD

In an input program: let the next DATA LIST read the last record again.

Syntax

REREAD [FILE='path' | handle] [COLUMN = expression].

COLUMN makes that column of the record column 1 for the DATA LIST (default 1). FILE names the data of the DATA LIST to reread (default: the last DATA LIST’s); a DATA LIST that reads other data ignores the REREAD. Of several REREAD commands in a row the last counts.

Example

DATA LIST /kind 10-14 (A).
DO IF kind = 'BELT'.
REREAD.
DATA LIST /cost 15-18 (DOLLAR,2).
END CASE.
END IF.

statscraft help REREAD prints the same text in the terminal. All commands

Statscraft 0.61.0, release v0.61.0

REPEATING DATA

In an input program or FILE TYPE: one case per repeating group of a record.

Syntax

REPEATING DATA [FILE='path' | handle] [/ENCODING='UTF-8'] /STARTS=column[-column]
    /OCCURS=n [/LENGTH=n] [/CONTINUED[=column[-column]]] [/ID=columns=var]
    [/TABLE | /NOTABLE] /DATA=variables as on DATA LIST.

STARTS, OCCURS, LENGTH and the end column on STARTS take a number or a variable.

Reads OCCURS groups from the record the last DATA LIST read, starting in column STARTS; the columns on DATA count from the start of a group. A group is LENGTH columns, by default up to the last variable or skip. Each group gives a case with the values of the other variables spread to it. CONTINUED: groups that do not fit before the end column (default 80, or the longest record) go on in the next records, from the column given (default 1); ID checks that an identifier on those records matches.

OCCURS missing or below 1 gives no case.

Example

DATA LIST /truck 1-3 nload 7-8.
REPEATING DATA STARTS=10 /OCCURS=nload
 /DATA=cargo 1-6 (A) crates 8-9.

statscraft help REPEATING DATA prints the same text in the terminal. All commands

Statscraft 0.61.0, release v0.61.0

FILE TYPE

Start the definition of a file with several kinds of records.

Syntax

FILE TYPE MIXED | GROUPED | NESTED [FILE='path' | handle] [ENCODING='name']
    RECORD=[var] columns [(format)] [CASE=[var] columns [(format)]]
    [WILD=WARN | NOWARN] [DUPLICATE=WARN | NOWARN | CASE] [MISSING=WARN | NOWARN]
    [ORDERED=YES | NO].

RECORD TYPE value … / DATA LIST … pairs follow, then END FILE TYPE.

MIXED: each record of a listed type is a case; others are skipped. GROUPED: the records with one CASE value make one case (CASE required). NESTED: the RECORD TYPE commands go from the highest level to the lowest; each lowest-level record is a case with the values of the records above it. Defaults: WILD=NOWARN (WARN for grouped), DUPLICATE and MISSING WARN for grouped and NOWARN for nested, ORDERED=YES (grouped only); DUPLICATE=CASE (nested) makes a case of a record that has no records below it.

Example

FILE TYPE GROUPED RECORD=#kind 6 CASE=runner 1-4.
RECORD TYPE 1.
DATA LIST /club 8-9 (A).
RECORD TYPE 2.
DATA LIST /sprint 8-10.
END FILE TYPE.

statscraft help FILE TYPE prints the same text in the terminal. All commands

Statscraft 0.61.0, release v0.61.0

RECORD TYPE

Inside FILE TYPE: the record types the following DATA LIST reads.

Syntax

RECORD TYPE value [value ...] | OTHER [SKIP] [CASE=columns] [DUPLICATE=WARN | NOWARN]
    [MISSING=WARN | NOWARN] [SPREAD=YES | NO].

Values are numbers, or quoted strings for a string record identifier. OTHER stands for every type not named before and comes last. SKIP passes over the records. CASE gives other columns for the case identifier; DUPLICATE (grouped) and MISSING apply to these types only. SPREAD=NO (nested): the values go to the first case built under the record only.

Example

RECORD TYPE 11, 12, 13.
DATA LIST /team 4 age 5-6.

statscraft help RECORD TYPE prints the same text in the terminal. All commands

Statscraft 0.61.0, release v0.61.0

END FILE TYPE

End a FILE TYPE definition and read the file.

Syntax

END FILE TYPE.

Example

FILE TYPE MIXED RECORD=rectype 1-2.
RECORD TYPE 13.
DATA LIST /team 4 minutes 7-9.
END FILE TYPE.

statscraft help END FILE TYPE prints the same text in the terminal. All commands

Statscraft 0.61.0, release v0.61.0

SPLIT FILE

Run each procedure once per run of consecutive cases that share the split values.

Syntax

SPLIT FILE [LAYERED | SEPARATE] BY varlist.
SPLIT FILE OFF.

A group ends where a split variable changes value, so sort the cases first.

LAYERED (the default) shows the groups in one table, with the split variables as the outermost row labels; SEPARATE gives every group tables of its own. AGGREGATE ignores the split; SORT CASES turns it off. The split is kept with the dataset.

Example

SPLIT FILE SEPARATE BY region.

statscraft help SPLIT FILE prints the same text in the terminal. All commands

Statscraft 0.61.0, release v0.61.0

FILTER

Leave out of procedures the cases whose filter value is 0 or missing.

Syntax

FILTER BY var.
FILTER OFF.

The cases stay in the dataset. The filter is kept with the dataset, follows a rename and ends when the variable is deleted or the dataset replaced.

Example

GET FILE='survey.sav'.
COMPUTE app_user = (ch_app = 1).
FILTER BY app_user.
DESCRIPTIVES age spend.
FILTER OFF.
DESCRIPTIVES age spend.

The example reads the sample data file survey.sav, an invented customer survey; save it in the folder you run the syntax from.

Example output

Descriptive Statistics

VariableLabelNMeanStd DevMinimumMaximum
ageAge in years8639.9012.161864
spendMonthly spend in euros8439.2413.6515.7994.52
Valid N (listwise)84
Missing N (listwise)2

statscraft help FILTER prints the same text in the terminal. All commands

Statscraft 0.61.0, release v0.61.0

TEMPORARY

Make the changes that follow last only until the next procedure.

Syntax

TEMPORARY.

Transformations, labels, formats, SELECT IF, SAMPLE, N OF CASES, WEIGHT, FILTER and SPLIT FILE after it are undone once the following data pass (a procedure, EXECUTE or SAVE) is over, or at the end of the run. Variables that procedure adds stay.

Example

TEMPORARY.

statscraft help TEMPORARY prints the same text in the terminal. All commands

Statscraft 0.61.0, release v0.61.0

N OF CASES

Keep only the first n cases from the next data pass on.

Syntax

N OF CASES n.

The limit applies after SELECT IF and SAMPLE, wherever they stand in the pass.

Example

N OF CASES 100.

statscraft help N OF CASES prints the same text in the terminal. All commands

Statscraft 0.61.0, release v0.61.0

N

Short for N OF CASES.

Syntax

N n.

The same command as N OF CASES: the active dataset keeps only its first n cases. A larger n than before has no effect.

Example

N 50.

statscraft help N prints the same text in the terminal. All commands

Statscraft 0.61.0, release v0.61.0

SAMPLE

Keep a random sample of the cases.

Syntax

SAMPLE proportion.
SAMPLE n FROM m.

A proportion between 0 and 1 keeps each case with that chance; n FROM m keeps exactly n of the first m cases (fewer when there are fewer than m). Inside DO IF only the cases of the branch are sampled. The random numbers come from the generator SET RNG chooses, started by SET SEED or MTINDEX; a new session starts from the default seed.

Example

SAMPLE 500 FROM 3420.

statscraft help SAMPLE prints the same text in the terminal. All commands

Statscraft 0.61.0, release v0.61.0

BOOTSTRAP

Give the next procedure bootstrap bias, standard errors and confidence intervals.

Syntax

BOOTSTRAP [/SAMPLING METHOD=SIMPLE | STRATIFIED(STRATA=varlist) | RESIDUAL(RESIDUALS=varlist | PREDICTED=varlist) |
                 WILD(RESIDUALS=varlist | PREDICTED=varlist)]
  [/VARIABLES [TARGET=varlist] [INPUT=varlist]]
  [/CRITERIA [CILEVEL=95 | level] [CITYPE=PERCENTILE | BCA] [NSAMPLES=1000 | n]]
  [/MISSING [USERMISSING=EXCLUDE | INCLUDE]].

Keywords are written in full. The next procedure runs on the data and then again on n resamples drawn with replacement (within each stratum for STRATIFIED), with the generator SET SEED or MTINDEX starts. Cases with a missing value in a TARGET, INPUT or STRATA variable leave the analysis; user-missing values of nominal and ordinal variables count as valid with USERMISSING=INCLUDE. DESCRIPTIVES, FREQUENCIES, MEANS, CORRELATIONS, T-TEST, REGRESSION, CROSSTABS, EXAMINE, ONEWAY, NONPAR CORR, PARTIAL CORR, LOGISTIC REGRESSION, NOMREG, PLUM, UNIANOVA and GLM add Bias, Std. Error and the interval (percentile or BCa) to their main statistics; any other procedure warns and runs without resampling. RESIDUAL and WILD keep the cases and rebuild each TARGET variable (one residual or predicted-value variable for each, in order) as its predicted value plus a residual drawn from all cases (RESIDUAL; one case’s residuals for all targets) or plus its own residual with a random sign (WILD).

Example

BOOTSTRAP /VARIABLES INPUT=height weight /CRITERIA CITYPE=BCA NSAMPLES=2000.

statscraft help BOOTSTRAP prints the same text in the terminal. All commands

Statscraft 0.61.0, release v0.61.0

Transformations

命令功能 {#what-it-does}
COMPUTEAssign the value of an expression to a variable.
IFAssign a value only for the cases where a condition holds.
DO IFStart a block of transformations that run only where a condition holds.
ELSE IFStart the next conditional branch of a DO IF block.
ELSEStart the branch of a DO IF block for the cases no condition matched.
END IFEnd a DO IF block.
RECODEMap values of variables to new values.
COUNTCount, per case, how many variables hold one of the listed values.
SELECT IFKeep only the cases where a condition holds.
STRINGDeclare new string variables, filled with empty strings.
NUMERICDeclare new numeric variables, filled with system-missing.
LEAVEKeep the values of new variables from case to case instead of resetting them.
EXECUTERun the pending transformations.
DO REPEATRepeat transformations with stand-in names replaced by variables or values.
LOOPRepeat transformations for each case, with an index, a condition or both.
END LOOPEnd a LOOP, optionally when a condition holds.
BREAKLeave the innermost LOOP, usually inside DO IF.
VECTORName a range of variables, or new variables, as a vector for indexed use.
AUTORECODERecode values into consecutive integers in new variables, labeled with the old values.
RANKRanks, percentile groups, proportion estimates, normal and Savage scores as new variables.
DATEAdd date variables that count the cases of a time series.
PRINTShow the values of variables for every case, as lines of text.
PRINT EJECTLike PRINT, starting a new page each time it runs.
PRINT SPACEAdd blank lines to the PRINT output, for every case it runs on.
WRITEWrite the values of variables for every case to a text file.
CLEAR TRANSFORMATIONSUndo the transformations and dictionary changes since the last data pass.

All commands

Statscraft 0.61.0, release v0.61.0

COMPUTE

Assign the value of an expression to a variable.

Syntax

COMPUTE target = expression.

The command sets target to the value of the expression for every case. A new target is numeric with format F8.2; an existing one keeps its format and labels. A string target must exist first (STRING), and a longer text is cut to its width.

When a value the expression needs is missing (system-missing, or a user-missing value of the variable), the result is system-missing, except in functions that skip missing values, such as MEAN, SUM and NVALID, and in MISSING, SYSMIS and VALUE. Operators and functions are listed under the general rules on the command index and in statscraft help.

COMPUTE is a transformation: it runs when the next procedure or EXECUTE reads the data.

Example

GET FILE='survey.sav'.
COMPUTE spend_year = spend * 12.
COMPUTE channels = SUM(ch_web, ch_app, ch_phone, ch_store, ch_email).
COMPUTE days_in = DATEDIFF(interview_date, DATE.DMY(5, 10, 2026), 'days').
DESCRIPTIVES spend_year channels days_in.

The example reads the sample data file survey.sav, an invented customer survey; save it in the folder you run the syntax from.

Example output

Descriptive Statistics

VariableLabelNMeanStd DevMinimumMaximum
spend_year284462.11158.57163.561134.24
channels3002.081.0205
days_in30020.9812.82041
Valid N (listwise)284
Missing N (listwise)16

statscraft help COMPUTE prints the same text in the terminal. All commands

Statscraft 0.61.0, release v0.61.0

IF

Assign a value only for the cases where a condition holds.

Syntax

IF (condition) target = expression.

The parentheses around the condition are optional. The command sets target only for the cases where the condition is true; where it is false or missing the target keeps its value. A new target starts as system-missing (numeric, F8.2) for every case, so cases the condition leaves out stay missing. A string target must exist first (STRING). Several IF commands in a row are checked one after another, so a later one may overwrite an earlier one.

Example

GET FILE='survey.sav'.
IF (satisfaction <= 2 AND switching = 1) at_risk = 1.
IF (age >= 60 AND ch_app = 0) offline = 1.
RECODE at_risk offline (SYSMIS = 0).
FREQUENCIES at_risk offline.

The example reads the sample data file survey.sav, an invented customer survey; save it in the folder you run the syntax from.

Example output

at_risk

CategoryValueLabelFrequencyPercentValid PercentCumulative Percent
valid026989.6789.6789.67
valid13110.3310.33100
total300100

statscraft help IF prints the same text in the terminal. All commands

Statscraft 0.61.0, release v0.61.0

DO IF

Start a block of transformations that run only where a condition holds.

Syntax

DO IF (condition).

Followed by COMPUTE, IF, RECODE or nested DO IF commands, then optional ELSE IF (condition). and ELSE. branches, then END IF.

For each case the first branch whose condition is true runs. After a missing condition no later branch runs for that case.

Example

DO IF (age < 18).

statscraft help DO IF prints the same text in the terminal. All commands

Statscraft 0.61.0, release v0.61.0

ELSE IF

Start the next conditional branch of a DO IF block.

Syntax

ELSE IF (condition).

Inside a DO IF block: the commands that follow run for the cases where no earlier condition of the block was true and this one is. A case whose earlier condition was missing runs no later branch.

Example

ELSE IF (age < 65).

statscraft help ELSE IF prints the same text in the terminal. All commands

Statscraft 0.61.0, release v0.61.0

ELSE

Start the branch of a DO IF block for the cases no condition matched.

Syntax

ELSE.

Inside a DO IF block, after the ELSE IF branches: the commands that follow run for the cases no condition of the block matched. A case with a missing condition does not reach it.

Example

ELSE.

statscraft help ELSE prints the same text in the terminal. All commands

Statscraft 0.61.0, release v0.61.0

END IF

End a DO IF block.

Syntax

END IF.

Every DO IF needs its own END IF. Blocks may nest.

Example

END IF.

statscraft help END IF prints the same text in the terminal. All commands

Statscraft 0.61.0, release v0.61.0

RECODE

Map values of variables to new values.

Syntax

RECODE varlist (inputs = output) [(inputs = output) ...] [INTO newvars] [/ varlist ...].

inputs: values, low THRU high (with LOWEST or HIGHEST), MISSING, SYSMIS, ELSE.

(CONVERT), for a string into a numeric target: at its place, a string that reads as a number becomes that number and a blank one system-missing; other strings go on to the next (inputs).

output: a value, SYSMIS or COPY.

The first matching (inputs = output) wins. A value or range also matches user-missing values.

Without a match a variable keeps its value, and so does an existing INTO target; a new target becomes system-missing.

A string target of INTO must exist already. A quoted value longer than its variable is an error.

Example

GET FILE='survey.sav'.
RECODE satisfaction (1, 2 = 1) (3 = 2) (4, 5 = 3) (MISSING = SYSMIS) INTO sat3.
VALUE LABELS sat3 1 'Dissatisfied' 2 'Neutral' 3 'Satisfied'.
RECODE age (LOWEST THRU 34 = 1) (35 THRU 54 = 2) (55 THRU HIGHEST = 3) INTO age3.
RECODE ch_web TO ch_email (SYSMIS = 0).
FREQUENCIES sat3.

The example reads the sample data file survey.sav, an invented customer survey; save it in the folder you run the syntax from.

Example output

sat3

CategoryValueLabelFrequencyPercentValid PercentCumulative Percent
valid1Dissatisfied8628.6731.0531.05
valid2Neutral8528.3330.6961.73
valid3Satisfied10635.3338.27100
missingSystem237.67
total300100

statscraft help RECODE prints the same text in the terminal. All commands

Statscraft 0.61.0, release v0.61.0

COUNT

Count, per case, how many variables hold one of the listed values.

Syntax

COUNT target = varlist (values) [varlist (values) ...] [/ target = ...].

values: values, low THRU high (with LOWEST or HIGHEST), MISSING, SYSMIS.

A value or range counts user-missing values too; a string variable takes quoted values only.

Example

COUNT channels = q5_1 TO q5_5 (1) / unanswered = q1 q2 (MISSING).

statscraft help COUNT prints the same text in the terminal. All commands

Statscraft 0.61.0, release v0.61.0

SELECT IF

Keep only the cases where a condition holds.

Syntax

SELECT IF condition.

The command keeps the cases where the condition is true and drops the others, also those where it is missing. The cases are gone for every later command; after TEMPORARY the selection holds only for the next procedure. FILTER hides cases without deleting them. Like other transformations, it runs when the next procedure or EXECUTE reads the data.

Example

GET FILE='survey.sav'.
SELECT IF (region = 3).
FREQUENCIES satisfaction.
GET FILE='survey.sav'.
SELECT IF (age >= 30 AND age < 60 AND NOT MISSING(spend)).
DESCRIPTIVES age spend.

The example reads the sample data file survey.sav, an invented customer survey; save it in the folder you run the syntax from.

Example output

Descriptive Statistics

VariableLabelNMeanStd DevMinimumMaximum
ageAge in years20544.767.873059
spendMonthly spend in euros20538.2812.8113.6394.52
Valid N (listwise)205
Missing N (listwise)0

statscraft help SELECT IF prints the same text in the terminal. All commands

Statscraft 0.61.0, release v0.61.0

STRING

Declare new string variables, filled with empty strings.

Syntax

STRING names (Awidth) [/ names (Awidth) ...].

Each name must be new, and every case starts as an empty string. A string variable must exist before COMPUTE or IF can assign text to it; a longer text is cut to the width.

Example

STRING region_code (A2).

statscraft help STRING prints the same text in the terminal. All commands

Statscraft 0.61.0, release v0.61.0

NUMERIC

Declare new numeric variables, filled with system-missing.

Syntax

NUMERIC names [(format)] [/ names [(format)] ...].

Without a format the variables get F8.2. Each name must be new, and every case starts as system-missing. COMPUTE and IF make numeric variables too; NUMERIC is needed when a variable must exist first, for example inside a DO IF block or with a given format.

Example

NUMERIC score (F5.1) / flag.

statscraft help NUMERIC prints the same text in the terminal. All commands

Statscraft 0.61.0, release v0.61.0

LEAVE

Keep the values of new variables from case to case instead of resetting them.

Syntax

LEAVE varlist.

The variables must be new: made by the transformations since the data were last read, before LEAVE, and not scratch variables. A numeric one starts at 0 for the first case, a string one blank; each later case starts with the value the case before ended with.

In an input program the variables are not reset before each case.

Example

COMPUTE runsum = runsum + amount.
LEAVE runsum.

statscraft help LEAVE prints the same text in the terminal. All commands

Statscraft 0.61.0, release v0.61.0

EXECUTE

Run the pending transformations.

Syntax

EXECUTE.

The command reads the data once so that the pending transformations (COMPUTE, IF, RECODE, SELECT IF and the like) take effect. A procedure does the same, so EXECUTE is needed only before a command that does not read the data, or to see the new values in the data window.

Example

EXECUTE.

statscraft help EXECUTE prints the same text in the terminal. All commands

Statscraft 0.61.0, release v0.61.0

DO REPEAT

Repeat transformations with stand-in names replaced by variables or values.

Syntax

DO REPEAT standin = varlist | values [/ standin = varlist | values ...].
  transformation commands

END REPEAT [PRINT].

Every list must have as many items; the commands run once per item, each stand-in replaced by its item. A list holds existing variables (TO in file order, ALL) or new names (v1 TO v5), or numbers and quoted strings (1 TO 5 counts up). PRINT shows the generated commands.

Example

DO REPEAT r = region1 TO region5 / v = 1 TO 5.
COMPUTE r = (region = v).
END REPEAT.

statscraft help DO REPEAT prints the same text in the terminal. All commands

Statscraft 0.61.0, release v0.61.0

LOOP

Repeat transformations for each case, with an index, a condition or both.

Syntax

LOOP [var = first TO last [BY step]] [IF condition].
  transformation commands

END LOOP [IF condition].

The index runs from first to last by step (1 by default); the expressions may differ per case, a missing one skips the loop. IF on LOOP is checked before each iteration, IF on END LOOP after it. A loop without an index stops after SET MXLOOPS iterations (default 40). BREAK leaves the innermost loop.

Example

LOOP #i = 1 TO 5.
COMPUTE total = total + #i.
END LOOP.

statscraft help LOOP prints the same text in the terminal. All commands

Statscraft 0.61.0, release v0.61.0

END LOOP

End a LOOP, optionally when a condition holds.

Syntax

END LOOP [IF condition].

Example

LOOP.
COMPUTE x = x + 1.
END LOOP IF x >= 10.

statscraft help END LOOP prints the same text in the terminal. All commands

Statscraft 0.61.0, release v0.61.0

BREAK

Leave the innermost LOOP, usually inside DO IF.

Syntax

BREAK.

Example

LOOP #i = 1 TO 10.
DO IF v(#i) = 0.
BREAK.
END IF.
END LOOP.

statscraft help BREAK prints the same text in the terminal. All commands

Statscraft 0.61.0, release v0.61.0

VECTOR

Name a range of variables, or new variables, as a vector for indexed use.

Syntax

VECTOR name = first TO last [/ ...].
VECTOR prefix [, prefix ...] (n [format]) [/ ...].

The first form refers to existing variables, all numeric or all strings of one width; the second creates prefix1 to prefixn (F8.2, or the format given). v(i) reads an element in expressions and is a target of COMPUTE and IF. A vector lasts until the next procedure.

Example

VECTOR q = q1 TO q10 / new (5, F2).

statscraft help VECTOR prints the same text in the terminal. All commands

Statscraft 0.61.0, release v0.61.0

AUTORECODE

Recode values into consecutive integers in new variables, labeled with the old values.

Syntax

AUTORECODE [VARIABLES=] varlist /INTO newlist [/BLANK=VALID | MISSING] [/GROUP]
           [/DESCENDING] [/PRINT] [/APPLY TEMPLATE='file'] [/SAVE TEMPLATE='file'].

Valid values get 1, 2, … in ascending order (DESCENDING: descending), user-missing values the codes after them, still user-missing; system-missing stays missing. Each code is labeled with the value label or the value. GROUP uses one scheme for all variables, BLANK=MISSING makes a blank string user-missing. All cases are recoded, also those a filter leaves out. SAVE TEMPLATE writes the scheme of the first variable (the common one with GROUP or APPLY TEMPLATE) to a data file of the variables Source_ and Target_, the valid values only and their codes; a name without an extension gets .sat. APPLY TEMPLATE keeps those codes for those values and gives the other valid values the codes above the highest, in the order of the command, and then the user-missing ones (those of the first variable that has any); the variables must be of the type of the template and share its scheme. With both, the template written is the template applied plus the new values, also in the same file.

Example

AUTORECODE VARIABLES=country /INTO country_code /PRINT.

statscraft help AUTORECODE prints the same text in the terminal. All commands

Statscraft 0.61.0, release v0.61.0

RANK

Ranks, percentile groups, proportion estimates, normal and Savage scores as new variables.

Syntax

RANK [VARIABLES=]varlist [(A | D)] [varlist [(A | D)] ...] [BY varlist]
     [/RANK] [/RFRACTION] [/PERCENT] [/PROPORTION] [/N] [/NTILES(k)] [/SAVAGE] [/NORMAL]
     [/TIES=MEAN | LOW | HIGH | CONDENSE] [/FRACTION=BLOM | RANKIT | TUKEY | VW]
     [/PRINT=YES | NO] [/MISSING=EXCLUDE | INCLUDE].

Each function, given at most once and followed by INTO names if wished, adds one new variable per ranked variable; without any, RANK is done. A (ascending, the default) or D (the largest value first) applies to the variables before it back to the previous A or D. BY ranks within each combination of the BY values; a missing BY value forms a group of its own. With the sum of weights W: RFRACTION is the rank r divided by W, PERCENT that times 100, N is W, NTILES(k) the group 1 to k, the integer part of r k / (W + 1) plus 1. PROPORTION follows FRACTION: BLOM (r - 3/8) / (W + 1/4) (the default), RANKIT (r - 1/2) / W, TUKEY (r - 1/3) / (W + 1/3), VW r / (W + 1); NORMAL is its standard normal quantile and SAVAGE the exponential score. TIES gives tied values the mean (default), lowest or highest rank; CONDENSE ranks the distinct values 1, 2, 3. A missing value (user-missing unless INCLUDE) or a missing, zero or negative weight gives system-missing. Names after INTO are used in order; the others are the function’s first letter and the first seven characters of the name, then the function’s first three letters and 001, 002 when taken, then RNK, two letters and 01. Labels read RANK of salary (by the BY variables). PRINT=NO leaves out the table of the new variables. Within SPLIT FILE groups the ranks start over.

Example

RANK VARIABLES=salary (D) BY region /RANK /NTILES(4) INTO salary_q /TIES=LOW.

statscraft help RANK prints the same text in the terminal. All commands

Statscraft 0.61.0, release v0.61.0

DATE

Add date variables that count the cases of a time series.

Syntax

DATE keyword [start [period]] [keyword ...] [BY n].

keyword: YEAR QUARTER MONTH (long periods), WEEK DAY HOUR MINUTE SECOND (short periods), CYCLE, OBS; any start of the word, MINUTE from MI. Long and short do not mix.

Each keyword makes a numeric variable named keyword_; DATE_ (a string) shows them all, and CYCLE_ is added when the highest keyword has a period. Defaults: start 1 (HOUR, MINUTE, SECOND 0), period QUARTER 4, MONTH 12, DAY 7, HOUR 24, MINUTE and SECOND 60, none for the highest keyword except QUARTER. OBS needs a start and a period; CYCLE takes no period. QUARTER and MONTH give each other their start; with MONTH the quarter follows the month. BY n steps the lowest keyword and must divide its period. Earlier DATE variables are replaced. A table lists the new variables and their labels.

Example

DATE Y 1990 M 7.

statscraft help DATE prints the same text in the terminal. All commands

Statscraft 0.61.0, release v0.61.0

PRINT

Show the values of variables for every case, as lines of text.

Syntax

PRINT [OUTFILE='path'] [ENCODING='name'] [RECORDS=n] [TABLE | NOTABLE]
      /[line] item [item ...] [/[line] ...].

item: varlist, varlist first-last [(type[,decimals])], varlist (format list), ‘text’ [column], or * to end the variables a format applies to. Format list: formats such as F8.2, n(…) repeats, Tn goes to column n, nX skips n columns.

A transformation: the lines appear when the data are next read, case by case, one line per slash. A variable in its own print format is followed by a blank; one with a given format or columns is not. System-missing shows as a period. OUTFILE writes the lines to a file, each starting with a blank (the carriage control), replaced on each data pass.

TABLE shows where each variable goes.

Example

PRINT /id name (A10) score (F6.2).

statscraft help PRINT prints the same text in the terminal. All commands

Statscraft 0.61.0, release v0.61.0

PRINT EJECT

Like PRINT, starting a new page each time it runs.

Syntax

PRINT EJECT [OUTFILE='path'] [ENCODING='name'] [RECORDS=n] [TABLE | NOTABLE] /item ....

As PRINT. In the output each new page is a new table; in a file its first line starts with 1 in place of the blank. Usually inside DO IF, for headings.

Example

DO IF $CASENUM = 1.
PRINT EJECT /'Name' 1 'Score' 12.
END IF.

statscraft help PRINT EJECT prints the same text in the terminal. All commands

Statscraft 0.61.0, release v0.61.0

PRINT SPACE

Add blank lines to the PRINT output, for every case it runs on.

Syntax

PRINT SPACE [OUTFILE='path'] [ENCODING='name'] [expression].

The expression gives the number of lines (default 1); a fraction is cut off; a missing or negative number gives one line and a warning. Usually inside DO IF.

Example

PRINT SPACE.

statscraft help PRINT SPACE prints the same text in the terminal. All commands

Statscraft 0.61.0, release v0.61.0

WRITE

Write the values of variables for every case to a text file.

Syntax

WRITE [OUTFILE='path'] [ENCODING='name'] [BOM=YES | NO] [RECORDS=n] [TABLE | NOTABLE]
      /[line] item [item ...] [/[line] ...].

Items as on PRINT, in the write formats, with no blank between values and no carriage control. System-missing is written as blanks. Without OUTFILE the lines go to the output.

The file is replaced on each data pass; commands that name the same file in one pass write to it in case order. ENCODING: UTF-8 (default, no byte order mark), UTF-16, UTF-16LE, UTF-16BE or a code page such as windows-1252; a UTF encoding given by name gets a byte order mark unless BOM=NO.

Example

WRITE OUTFILE='scores.txt' /id (F4) score (F6.2).

statscraft help WRITE prints the same text in the terminal. All commands

Statscraft 0.61.0, release v0.61.0

CLEAR TRANSFORMATIONS

Undo the transformations and dictionary changes since the last data pass.

Syntax

CLEAR TRANSFORMATIONS.

The dataset goes back to how it was after the last command that read the data (a procedure, EXECUTE, SAVE, GET and the like) or the start of the run. Pending PRINT, WRITE and XSAVE never run. Settings, titles and files stay as they are.

Example

CLEAR TRANSFORMATIONS.

statscraft help CLEAR TRANSFORMATIONS prints the same text in the terminal. All commands

Statscraft 0.61.0, release v0.61.0

Procedures

命令功能 {#what-it-does}
FREQUENCIESFrequency tables, summary statistics and percentiles.
DESCRIPTIVESSummary statistics of numeric variables, optionally saved as z-scores.
CROSSTABSContingency tables with percentages, residuals and chi-square tests.
MULT RESPONSEFrequency tables and crosstabulations of multiple response groups and variables.
MEANSStatistics of dependent variables within groups of control variables.
SUMMARIZEStatistics of dependents within groups of control variables, optionally listing the cases.
OLAP CUBESStatistics of scale variables in nested groups, with differences between groups or variables.
CODEBOOKDictionary entries and summary statistics of variables and multiple response sets.
VALIDATEDATAFind suspicious variables, incomplete or duplicate IDs, empty cases and rule violations.
T-TESTOne-sample, independent-samples and paired-samples t tests with effect sizes.
ONEWAYOne-way analysis of variance with contrasts and post hoc comparisons.
CORRELATIONSPearson correlations with significance and case counts.
NONPAR CORRSpearman’s rho and Kendall’s tau-b rank correlations with significance.
PARTIAL CORRPartial correlations of variables controlling for others, with significance.
NPAR TESTSNonparametric tests: one-sample, two and k related samples, two and k independent samples.
NPTESTSNonparametric tests picked by measurement level: one sample, independent samples, related samples.
PROPORTIONSTests and confidence intervals for a proportion or a difference of two proportions.
EXAMINEDescriptives, percentiles, M-estimators, extreme values and normality tests, by factor cells.
REGRESSIONLinear regression with forced entry or removal and stepwise selection, residuals and diagnostics.
RELIABILITYReliability of a scale: Cronbach’s alpha, split-half and other models, item statistics and ICC.
WEIGHTED KAPPACohen’s weighted kappa: how well two raters agree on an ordered scale.
FLEISS MULTIRATER KAPPAFleiss’ kappa: how well several raters agree when they sort subjects into categories.
RATIO STATISTICSStatistics of the ratio of two positive variables, overall and within groups.
BAYES ONESAMPLEBayesian inference on one mean, proportion or Poisson rate: Bayes factors and posteriors.
BAYES RELATEDBayesian inference on the mean difference of paired measurements.
BAYES INDEPENDENTBayesian comparison of the means of two independent groups.
BAYES CORRELATIONBayesian inference on the Pearson correlation of every pair of variables.
BAYES ANOVABayesian one-way analysis of variance: a Bayes factor for the groups and posteriors of their means.
BAYES REGRESSIONBayesian linear regression: a Bayes factor for the model, posteriors, predictions and F tests.
BAYES REPEATEDBayesian one-way repeated measures analysis: a Bayes factor and posteriors of the condition means.
BAYES LOGLINEARBayesian test of independence in a two-way table, with simulated interaction terms.
POWER MEANS ONESAMPLEPower or sample size of a one-sample t-test of a mean.
POWER MEANS INDEPENDENTPower or group sizes of a t-test comparing the means of two independent groups.
POWER MEANS RELATEDPower or number of pairs of a paired t-test.
POWER PROPORTIONS ONESAMPLEPower or sample size of a test of one proportion against a hypothesized value.
POWER PROPORTIONS INDEPENDENTPower or group sizes of a test comparing two independent proportions.
POWER PROPORTIONS RELATEDPower or number of pairs of McNemar’s test of two paired proportions.
POWER ONEWAY ANOVAPower or group sizes of a one-way analysis of variance, its contrasts and pairwise comparisons.
POWER PEARSON ONESAMPLEPower or sample size of a test of one Pearson correlation against a hypothesized value.
POWER SPEARMAN ONESAMPLEPower or sample size of a test of one Spearman rank correlation against a hypothesized value.
POWER PARTIALCORRPower or sample size of a test of one partial correlation against a hypothesized value.
POWER UNIVARIATE LINEARPower or sample size of the F test of a set of predictors in a linear regression.
SIMPLANA simulation plan: distributions of the inputs, fitted to the data or given, their correlations and the targets of a model.
SIMRUNRuns a simulation plan: draws the inputs, computes the targets and describes their distributions.
BEGIN EXPRStarts a block of expressions that END EXPR saves as a model for SIMPLAN.
END EXPREnds the BEGIN EXPR block and writes its model file.
FACTORFactor analysis: principal components and six factoring methods, rotations, factor scores.
QUICK CLUSTERK-means clustering of cases into a given number of clusters.
CLUSTERHierarchical clustering of cases by one of 37 proximity measures and seven methods.
TWOSTEP CLUSTERClusters of cases from continuous and categorical variables, the number of clusters chosen by BIC or AIC.
DMCLUSTERAnother name for TWOSTEP CLUSTER.
DETECTANOMALYUnusual cases: peer groups by two-step clustering, an anomaly index and the variables behind it.
OPTIMAL BINNINGBins of scale variables: cuts chosen by MDLP against a guide variable, or by equal frequency.
KNNNearest neighbor analysis: classify or predict a target from the k most similar training cases.
NAIVEBAYESNaive Bayes classification of a categorical target, with forward selection of the predictors.
AIMAttribute importance: how much each variable sets every group (cluster) apart from all cases.
SELECTPREDScreens a long list of predictors and ranks them one by one by how well each relates to a target.
RESPONSE RATEResponse rates of a numerator over a denominator in each group, with cumulative rates and limits.
ADPPrepares a target and its inputs for modelling and writes the preparation as syntax.
PROXIMITIESSimilarities, dissimilarities or distances between cases or variables by one of 37 measures.
PROXSCALMultidimensional scaling of one or more proximity matrices by majorization, with optimal transformations.
PREFSCALMultidimensional unfolding of preferences or proximities between row and column objects, with penalized stress.
ALSCALMultidimensional scaling of proximity matrices, symmetric, asymmetric or rectangular, by alternating least squares on squared distances.
ORTHOPLANGenerates an orthogonal main-effects plan of profiles for a conjoint study.
PLANCARDSShows the profiles of a conjoint plan as a list or as one card per profile.
CONJOINTPart-worth utilities and importances from rankings or scores of the profiles of a plan.
DISCRIMINANTLinear discriminant analysis with direct or stepwise entry and classification of cases.
CORRESPONDENCECorrespondence analysis: rows and columns of a two-way table as points in a few dimensions.
MULTIPLE CORRESPONDENCEMultiple correspondence (homogeneity) analysis: cases and categories of several nominal variables as points in a few dimensions.
CATPCACategorical principal components: quantify each variable by optimal scaling (spline, ordinal, nominal, multiple nominal or numeric) and reduce them to a few components.
CATREGCategorical regression: quantify a response and its predictors by optimal scaling (spline, ordinal, nominal or numeric) so that a linear model fits best, with ridge, lasso and elastic net penalties.
HOMALSHomogeneity analysis in the older syntax: MULTIPLE CORRESPONDENCE with variables read as categories 1 to a stated largest value.
PRINCALSNonlinear principal components in the older syntax: CATPCA with variables read as categories 1 to a stated largest value.
OVERALSNonlinear canonical correlation analysis: what two or more sets of variables, each quantified at its own level, have in common.
ANACORCorrespondence analysis in the older syntax: CORRESPONDENCE with its own normalization names and defaults.
LOGISTIC REGRESSIONBinary logistic regression with categorical covariates, stepwise selection and case diagnostics.
DMLOGISTICAnother name for LOGISTIC REGRESSION.
NOMREGMultinomial logistic regression: a nominal dependent variable on factors and covariates.
MVAMissing value analysis: where values are missing, how that relates to the other variables, and estimates that allow for it.
HILOGLINEARHierarchical loglinear models of a multiway table of counts, with backward elimination.
LOGLINEARGeneral loglinear and logit models of a table of counts, with contrasts, cell weights and generalized residuals.
GENLOGGeneral loglinear and logit models of a table of counts, with cell weights, covariates and contrasts.
PROBITProbit and logit models of response counts out of subject counts, with effective levels.
CURVEFITFit up to eleven curves of one independent variable, or of time, by least squares.
WLSWeighted least squares: weights from a power of a source variable, or a given weight.
MODEL PROGRAMName the parameters of a nonlinear model and give their starting values; the transformations after it define the model.
DERIVATIVESStart the derivatives program of the model program.
CLEAR MODEL PROGRAMSDrop the model program and the derivatives program of the last MODEL PROGRAM.
NLRNonlinear regression by least squares (Levenberg-Marquardt) for the model of the last MODEL PROGRAM.
CONSTRAINED FUNCTIONSStart the program that computes the constrained functions of the next CNLR.
CNLRConstrained nonlinear regression: least squares or a loss function of your own, under bounds, linear constraints and constrained functions.
MULTIPLE IMPUTATIONMultiple imputation: several completed copies of the data with plausible values in place of the missing ones.
PLUMOrdinal regression: a cumulative link model of an ordered dependent variable.
QUANTILE REGRESSIONLinear regression of a chosen quantile of the dependent variable, fitted by linear programming.
PLSPartial least squares regression of one or more dependent variables on many, possibly collinear, predictors.
GENLINGeneralized linear models: normal, binomial, Poisson, gamma, inverse Gaussian, negative binomial and ordinal responses.
UNIANOVAGeneral linear model of one dependent variable: factorial ANOVA, ANCOVA and regression.
GLMGeneral linear model: one dependent variable as in UNIANOVA, several (multivariate analysis of variance and covariance), or repeated measures with WSFACTOR.
MANOVAAnalysis of variance and covariance for one or several dependents, with nested and pooled terms, partitions and chosen error terms.
MIXEDLinear mixed model: fixed effects with random effects of subjects and correlated repeated measures.
VARCOMPVariance components: how much each random effect of a linear model adds to the variance of the dependent variable.
GENLINMIXEDGeneralized linear mixed model: a target with a normal, binomial, multinomial, gamma, inverse Gaussian, Poisson or negative binomial distribution and a link, fixed effects, random effects of subjects and repeated measures.
COXREGCox proportional hazards regression of survival times, with strata, categorical covariates, stepwise selection and time-dependent covariates.
TIME PROGRAMStart the transformations that define time-dependent covariates for the next COXREG.
CLEAR TIME PROGRAMDrop the time-dependent covariates of the last TIME PROGRAM.
ANOVAAnalysis of variance for factorial designs with covariates, the older form with MCA tables.
TREEA decision tree grown by CHAID, exhaustive CHAID, CRT or QUEST, with gain tables, rules and saved predictions.
DMTREEAnother name for TREE.
MLPMultilayer perceptron: a neural network with one or two hidden layers that predicts scale dependents and classifies categorical ones.
RBFRadial basis function network: Gaussian hidden units at two-step clusters and least squares output weights.
GRAPHOne chart: summaries by category as bars, lines, areas, a pie, points with error bars, a Pareto chart or ranges, a histogram, a scatterplot or a scatterplot matrix.
GGRAPHA chart from a graph dataset and a chart program in BEGIN GPL: bars (clustered, stacked), lines, areas, points, a pie or a histogram.
BEGIN GPLThe chart program of the GGRAPH command right before it, up to END GPL.
IGRAPHThe older chart command: bars, lines, areas, pies, boxes, error bars, histograms and scatterplots built from variables placed on axes and legends.
XGRAPHCharts from one expression: summaries as bars or lines, clustered, stacked and paneled, population pyramids, binned histograms, dot plots and boxes.
PPLOTProbability plots: Q-Q or P-P plots of variables against a test distribution.
NPPLOTAnother name for PPLOT.
ROCROC curve of test variables against a state, with the area under the curve.
DMROCAnother name for ROC.
ROC ANALYSISROC curves with paired or two-group comparisons of their areas, precision-recall curves and classifier metrics.
SPCHARTControl charts (X-bar with R or s, individuals, p, np, c, u) and the process capability chart.
KMKaplan-Meier survival estimates by factor level and stratum, with tests that compare the levels.
K-MAnother name for KM.
SURVIVALActuarial life tables over fixed time intervals, with the Wilcoxon (Gehan) comparison of groups.
REPORTCase listings and summary statistics by break groups, laid out as a report.
MATRIXRun a program in the matrix language, up to END MATRIX.

All commands

Statscraft 0.61.0, release v0.61.0

FREQUENCIES

Frequency tables, summary statistics and percentiles.

Syntax

FREQUENCIES [/]VARIABLES=varlist [/FORMAT=[NOTABLE | LIMIT(n)] [AVALUE | DVALUE | AFREQ | DFREQ]]
            [/MISSING=INCLUDE] [/STATISTICS=[stat ...]] [/PERCENTILES=p ...] [/NTILES=n]
            [/GROUPED=varlist [(width) | (boundary, ...)]] [/ORDER=ANALYSIS | VARIABLE]
            [/BARCHART=[MIN(n)] [MAX(n)] [FREQ[(n)] | PERCENT[(n)]]]
            [/PIECHART=[MIN(n)] [MAX(n)] [FREQ | PERCENT] [MISSING | NOMISSING]]
            [/HISTOGRAM=[MIN(n)] [MAX(n)] [FREQ[(n)]] [NORMAL | NONORMAL]].

stat: MEAN SEMEAN MEDIAN MODE STDDEV VARIANCE SKEWNESS SESKEW KURTOSIS SEKURT RANGE MINIMUM MAXIMUM SUM DEFAULT ALL NONE. STATISTICS alone or DEFAULT is MEAN STDDEV MINIMUM MAXIMUM; /STATS works too.

A frequency table per variable: valid values, then missing ones, with percent, valid percent and cumulative percent. NOTABLE leaves the tables out, LIMIT(n) the tables with more than n values.

DVALUE, AFREQ and DFREQ order the values by descending value or by frequency (ties ascending by value); they are ignored when percentiles or a histogram are asked for. A Statistics table, one for all variables (ORDER=VARIABLE: one per variable, before its frequency table), shows the valid and missing counts and the statistics; it appears when statistics or percentiles are asked for, or when a frequency table is left out. Percentiles use (W + 1) p, the median is the 50th percentile and is left out with AFREQ and DFREQ; MODE shows the smallest of tied modes, with a note. NTILES=n adds the n - 1 points that cut the cases into n equal groups (n up to 1000); several PERCENTILES and NTILES add up.

GROUPED treats the values as groups for the median and percentiles: alone the values are group midpoints, (width) groups that wide around each value, (boundaries) the given groups; a value outside the boundaries falls in an open group, where percentiles are undefined (shown empty).

INCLUDE makes user-missing values valid. Weighted when a weight variable is set; a case with a missing, zero or negative weight is left out. String variables get the table and the counts only.

Charts: one per variable for each chart subcommand; BARCHART and HISTOGRAM exclude each other.

BARCHART has a bar per valid value, in the order of the table: counts, or with PERCENT shares of the valid cases. PIECHART has a slice per valid value plus one for all missing values (none with NOMISSING): counts, or with PERCENT shares of the whole pie. HISTOGRAM (numeric variables) counts the valid values in equal bins: Sturges’ number of bins, a width of 1, 2 or 5 times a power of ten (at least 1 for whole values); NORMAL adds the normal curve of all valid values. MIN(n) and MAX(n) leave out the values outside; the n of FREQ(n) or PERCENT(n) is the top of the axis. Of FREQ and PERCENT, MISSING and NOMISSING, NORMAL and NONORMAL the first given counts. A chart comes as its numbers: a data table in the text output, its description with –json, and a Vega-Lite specification with –vega-lite.

Example

GET FILE='survey.sav'.
FREQUENCIES region satisfaction.
FREQUENCIES age spend /FORMAT=NOTABLE /STATISTICS=MEAN MEDIAN STDDEV MINIMUM MAXIMUM.
FREQUENCIES education /BARCHART PERCENT.

The example reads the sample data file survey.sav, an invented customer survey; save it in the folder you run the syntax from.

Example output

Overall satisfaction with the service

CategoryValueLabelFrequencyPercentValid PercentCumulative Percent
valid1Very dissatisfied206.677.227.22
valid2Dissatisfied662223.8331.05
valid3Neutral8528.3330.6961.73
valid4Satisfied632122.7484.48
valid5Very satisfied4314.3315.52100
missing9Don’t know237.67
total300100

statscraft help FREQUENCIES prints the same text in the terminal. All commands

Statscraft 0.61.0, release v0.61.0

DESCRIPTIVES

Summary statistics of numeric variables, optionally saved as z-scores.

Syntax

DESCRIPTIVES [/]VARIABLES=varlist [/STATISTICS=stat ...] [/SORT=[key] [(A | D)]]
             [/MISSING=VARIABLE | LISTWISE [INCLUDE]] [/SAVE].

stat: MEAN SEMEAN STDDEV VARIANCE KURTOSIS SKEWNESS RANGE MINIMUM MAXIMUM SUM DEFAULT ALL.

DEFAULT is MEAN STDDEV MINIMUM MAXIMUM; N is always shown. Weighted when a weight variable is set.

SORT lists the variables by key (MEAN SEMEAN STDDEV VARIANCE KURTOSIS SKEWNESS RANGE MIN MAX SUM or NAME), ascending (A, the default) or descending (D); without a key it is the mean. A variable without the statistic goes last. The key need not be among the statistics shown.

MISSING=VARIABLE (the default) leaves out the missing values of each variable on its own; LISTWISE leaves out a case missing on any listed variable; INCLUDE counts user-missing values.

The row Valid N (listwise) counts the cases valid on every listed variable. String variables get no statistics; a warning names them. var (name) in the list adds a z-score under that name; SAVE adds one for every variable, named Z plus the variable name (ZSC001 to ZSC099, STDZ01 to STDZ09, ZZZZ01 to ZZZZ09, ZQZQ01 to ZQZQ09 when that name is taken), labeled Zscore: plus the label.

Example

GET FILE='survey.sav'.
DESCRIPTIVES age spend satisfaction.
DESCRIPTIVES spend /STATISTICS=MEAN SEMEAN STDDEV MIN MAX.
DESCRIPTIVES age spend /SAVE.

The example reads the sample data file survey.sav, an invented customer survey; save it in the folder you run the syntax from.

Example output

Descriptive Statistics

VariableLabelNMeanStd DevMinimumMaximum
ageAge in years30045.7413.701884
spendMonthly spend in euros28438.5113.2113.6394.52
satisfactionOverall satisfaction with the service2773.161.1615
Valid N (listwise)261
Missing N (listwise)39

statscraft help DESCRIPTIVES prints the same text in the terminal. All commands

Statscraft 0.61.0, release v0.61.0

CROSSTABS

Contingency tables with percentages, residuals and chi-square tests.

Syntax

CROSSTABS [/][TABLES=]rowvars BY colvars [BY layervars ...] [/TABLES=...]
          [/VARIABLES=varlist (min, max) [varlist (min, max) ...]  (before TABLES)]
          [/CELLS=COUNT ROW COLUMN TOTAL EXPECTED RESID SRESID ASRESID ALL NONE]
          [/STATISTICS=CHISQ PHI CC LAMBDA UC BTAU CTAU GAMMA D ETA CORR KAPPA RISK MCNEMAR CMH[(1)] ALL NONE] [/MISSING=TABLE | INCLUDE | REPORT]
          [/FORMAT=AVALUE | DVALUE TABLES | NOTABLES]
          [/COUNT=[ASIS | CASE | CELL] [ROUND | TRUNCATE]] [/BARCHART]
          [/WRITE[=NONE | CELLS | ALL]]
          [/METHOD=MC [CIN(99)] [SAMPLES(10000)] | EXACT [TIMER(5)]].

The command makes one contingency table per pair of row and column variable; layer variables split it into blocks. The first TABLES= keyword may be left out. A Case Processing Summary comes first: the valid, missing and total cases of each table (weighted). CELLS defaults to COUNT; CELLS alone is COUNT ROW COLUMN TOTAL. Percentages run from 0 to 100. FORMAT=DVALUE orders the rows from the highest value; columns stay ascending. NOTABLES, like CELLS=NONE, drops the tables and keeps the statistics. MISSING=TABLE (default) leaves out a case missing on any variable of the table; INCLUDE keeps user-missing values as categories.

STATISTICS alone is CHISQ: Pearson, likelihood ratio, linear-by-linear (numeric variables), and for a 2 x 2 table Fisher’s exact test (on whole counts, rounded or truncated by COUNT) and the continuity correction. ALL is every statistic, CMH with 1. Each measure gives its value, asymptotic standard error, approximate T and significance; a table with one row or column gets none but kappa. Symmetric Measures holds PHI (phi, Cramer’s V), CC (contingency coefficient), BTAU, CTAU (Kendall’s tau-b, tau-c), GAMMA and CORR (Spearman, Pearson; numeric only). Directional Measures holds LAMBDA (lambda, Goodman and Kruskal’s tau), UC (uncertainty coefficient), D (Somers’ d) and ETA (numeric).

KAPPA uses the square table over the values of both variables (same type), unseen pairs counted 0. MCNEMAR adds the exact McNemar test (2 x 2) or McNemar-Bowker (larger) to the chi-square table, for rows and columns with the same values. RISK gives a Risk Estimate table for 2 x 2 tables: the odds ratio and each column’s risk, with 95% intervals. CMH treats the layers as strata of 2 x 2 tables: Breslow-Day and Tarone (homogeneity, over the strata with cases in the first row and the first column; df is their number less one), Cochran and Mantel-Haenszel (conditional independence), and the common odds ratio with its 95% interval, tested against the value in parentheses.

COUNT makes weighted counts whole before anything is computed: CASE each case’s weight, CELL each cell’s count, by ROUND or TRUNCATE; a row or column whose cells all become 0 then drops out. A keyword left out is CELL or ROUND. Without COUNT, or with ASIS, the weights stay as they are.

VARIABLES switches to integer mode: a range follows each list and covers all of it, and values are cut to whole numbers. Rows and columns are every value of the range, with or without cases (a range of more than 1000 values lists the values that occur, with a warning); a value outside it makes the case missing. Statistics use the values that occur. TABLES then names only variables of VARIABLES, and TO and ALL follow their order there. MISSING=REPORT (integer mode only) shows user-missing row and column values, marked (missing): their cells hold counts only, stay out of totals, percentages and statistics, and the cases count as missing.

BARCHART adds a clustered bar chart per table: a cluster per row category, a bar per column category, counts summed over the layers; with MISSING=REPORT the user-missing values that occur take part too, marked (missing). FORMAT also accepts BOX, NOBOX, INDEX, NOINDEX, PIVOT and NOPIVOT, which change nothing, with one warning.

WRITE writes one record per cell to the file of the PROCEDURE OUTPUT before the command, after an Output File Summary table. Columns 1-16 hold the split-file group (from 1), table number and count as whole numbers; then come the row, column and control values in 8-column fields (whole numbers in integer mode, else as the variable prints, text to the left). Records go a table column at a time, the last control variable changing slowest. CELLS (also bare WRITE) writes the non-empty cells without a missing value, or with them under MISSING=INCLUDE or REPORT; ALL (integer mode only) every cell of the ranges. A long string variable or more than eight dimensions is an error.

METHOD adds significances from the tables with the observed row and column totals, next to the asymptotic ones, on whole counts (rounded, or truncated with TRUNCATE). EXACT enumerates those tables: the chi-square table gets the exact two-sided significance and point probability of Pearson, likelihood ratio, Fisher’s test (any size) and linear-by-linear (also one-sided), the McNemar-Bowker line of the chi-square table, and the measures tables an Exact Significance column for every measure except gamma, eta and the symmetric lambda. TIMER(minutes) bounds each statistic (0: no bound); one that runs over or needs too much memory keeps only its asymptotic value, with a warning. MC instead draws SAMPLES random tables with those totals from the SET SEED generator and shows the share at least as extreme, with its interval at CIN percent; this covers gamma and the symmetric lambda too. McNemar-Bowker tests symmetry, so its draws split each pair of mirror cells by a fair coin, as its exact test does, and do not keep the totals. CMH stays asymptotic. A warning names gamma and the symmetric lambda under EXACT, where they are shown without an exact value.

Example

GET FILE='survey.sav'.
CROSSTABS /TABLES=recommend BY region.
CROSSTABS /TABLES=switching BY age_group /CELLS=COUNT COLUMN /STATISTICS=CHISQ.
WEIGHT BY weight.
CROSSTABS /TABLES=satisfaction BY gender BY region /CELLS=COLUMN.

The example reads the sample data file survey.sav, an invented customer survey; save it in the folder you run the syntax from.

Example output

Would recommend us to a friend by Region

Would recommend us to a friendStatisticRegion / NorthRegion / SouthRegion / EastRegion / WestTotal
NoCount20233733113
YesCount55394449187
TotalCount75628182300

statscraft help CROSSTABS prints the same text in the terminal. All commands

Statscraft 0.61.0, release v0.61.0

MULT RESPONSE

Frequency tables and crosstabulations of multiple response groups and variables.

Syntax

MULT RESPONSE [/]GROUPS=name ['label'] (varlist (value)) | (varlist (min, max)) [name ...]
              [/VARIABLES=varlist (min, max) [varlist (min, max) ...]]
              [/FREQUENCIES=items]
              [/TABLES=items BY items [BY items ...] [(PAIRED)] [/items BY ...]]
              [/MISSING=[TABLE | MDGROUP | MRGROUP] [INCLUDE]]
              [/FORMAT=[LABELS | NOLABELS] [TABLE | CONDENSE | ONEPAGE] [DOUBLE]]
              [/BASE=CASES | RESPONSES] [/CELLS=[COUNT] [ROW] [COLUMN] [TOTAL] [ALL]].

GROUPS, VARIABLES, FREQUENCIES and TABLES come in this order, before the others; at least one of GROUPS and VARIABLES and one of FREQUENCIES and TABLES. One value makes a dichotomy group (its categories are the variables with that value), two a category group (the values from min to max, counted over all its variables). Groups exist only in this command.

items: groups, and variables named on VARIABLES; TO follows their order there. Values are truncated to whole numbers; values out of range do not count. Empty categories are left out.

A case is missing for a group with no counted value; MDGROUP and MRGROUP leave out a case missing on any variable of a dichotomy or category group (MRGROUP also for a value out of range); INCLUDE counts user-missing values. FREQUENCIES: responses, percent of responses and percent of cases. TABLES: counts, and the percentages CELLS asks for (ALL without keywords), based on cases or with BASE=RESPONSES on responses. PAIRED pairs the first variable of a category group with the first of another, and so on; its percentages are based on responses. NOLABELS and CONDENSE show values for category groups and variables; ONEPAGE and DOUBLE only change printed layout and are ignored with a warning. Weights count as they are.

Example

GET FILE='survey.sav'.
MULT RESPONSE GROUPS=channels 'Channels used' (ch_web TO ch_email (1))
  /FREQUENCIES=channels.
MULT RESPONSE GROUPS=channels 'Channels used' (ch_web TO ch_email (1))
  /VARIABLES=age_group (1, 4)
  /TABLES=channels BY age_group /CELLS=COUNT COLUMN /BASE=CASES.

The example reads the sample data file survey.sav, an invented customer survey; save it in the folder you run the syntax from.

Example output

Channels used Frequencies

Channels usedResponses / NResponses / PercentPercent of Cases
Website21233.9774.39
Mobile app8613.7830.18
Phone14923.8852.28
Store6510.4222.81
Email11217.9539.30
Total624100218.95

channels is a dichotomy group counting the value 1.

statscraft help MULT RESPONSE prints the same text in the terminal. All commands

Statscraft 0.61.0, release v0.61.0

MEANS

Statistics of dependent variables within groups of control variables.

Syntax

MEANS [TABLES=]deps [BY controls [BY ...]] [/deps BY ...] [/CELLS=cell ...]
      [/STATISTICS=ANOVA | LINEARITY | NONE] [/MISSING=TABLE | INCLUDE | DEPENDENT].

cell: MEAN COUNT STDDEV MEDIAN GMEDIAN SEMEAN SUM MIN MAX RANGE VARIANCE KURT SEKURT SKEW SESKEW FIRST LAST NPCT SPCT NPCT(var) SPCT(var) HARMONIC GEOMETRIC DEFAULT ALL; DEFAULT is MEAN COUNT STDDEV. GMEDIAN is the grouped median: each value is the midpoint of its interval.

NPCT(var) and SPCT(var) give the percent of the N and of the sum of the cases in the same category of var, which must be a control of every table list (all cases on its Total rows).

One Report table per dependent and combination of controls: every group of the first control, the next nested inside, each level with a Total. A Case Processing Summary per table list.

A string dependent gets COUNT, FIRST and LAST only. ANOVA gives the analysis of variance by the first control with eta; LINEARITY adds the linear term and r (three or more numeric groups).

Without /MISSING each dependent with its controls leaves out its own missing cases; any /MISSING leaves out cases missing on any variable of the list (INCLUDE: user-missing values count; DEPENDENT: they count for the controls only). Weighted when a weight variable is set.

Example

GET FILE='survey.sav'.
MEANS spend BY region.
MEANS spend age BY age_group BY gender /CELLS=MEAN COUNT STDDEV.
MEANS satisfaction BY education /STATISTICS=ANOVA.

The example reads the sample data file survey.sav, an invented customer survey; save it in the folder you run the syntax from.

Example output

Report: Monthly spend in euros by Region

RegionMeanNStd. Deviation
North36.147111.89
South40.505916.44
East38.477613.51
West39.197811.10
Total38.5128413.21

statscraft help MEANS prints the same text in the terminal. All commands

Statscraft 0.61.0, release v0.61.0

SUMMARIZE

Statistics of dependents within groups of control variables, optionally listing the cases.

Syntax

SUMMARIZE [TABLES=]deps [BY controls [BY ...]] [/[TABLES=]deps BY ...] [/TITLE='text']
          [/FOOTNOTE='text'] [/CELLS=cell ... | NONE]
          [/MISSING=[EXCLUDE | INCLUDE | DEPENDENT] [VARIABLE | TABLE]]
          [/FORMAT=[NOLIST | LIST [LIMIT=n] | VALIDLIST [LIMIT=n]] [CASENUM | NOCASENUM]
                   [TOTAL | NOTOTAL] [MISSING='text']]
          [/STATISTICS=ANOVA | LINEARITY | ALL | NONE].

cell: as on MEANS; DEFAULT (MEAN COUNT STDDEV) when CELLS is left out, ALL for every cell.

Each table list gives a Case Processing Summary and one Case Summaries table per combination of controls (one from each BY): the groups of the first control with the next nested inside, each level ending in a Total, one row per cell statistic and one column per dependent. LIST adds the cases of each innermost group, numbered unless NOCASENUM; VALIDLIST lists only cases valid on every dependent; LIMIT=n works on the first n cases only. LIST and VALIDLIST allow one table list. NOTOTAL keeps the total rows without their label. MISSING=‘text’ replaces the period of a system-missing value in the listing. VARIABLE (default) drops a case from the dependents it is missing on, TABLE from all of them when it is missing on any. A case missing on a control is always dropped; INCLUDE counts user-missing values as valid, DEPENDENT only for controls. A string dependent gets COUNT, FIRST, LAST and NPCT only. ANOVA and LINEARITY work as on MEANS, by each control of the first BY. TITLE and FOOTNOTE (\n breaks a line) name the summary tables. A subcommand given twice: the last one counts. Weighted when a weight variable is set.

Example

SUMMARIZE TABLES=income spend BY region /FORMAT=LIST LIMIT=20 NOCASENUM
  /CELLS=COUNT MEAN MAX /TITLE='Spending by region'.

statscraft help SUMMARIZE prints the same text in the terminal. All commands

Statscraft 0.61.0, release v0.61.0

OLAP CUBES

Statistics of scale variables in nested groups, with differences between groups or variables.

Syntax

OLAP CUBES summaryvars BY groupvars [BY groupvars ...] [/CELLS=cell ... | NONE]
           [/CREATE ['label' | DEFAULT ...] GAC | GPC | GAC GPC (groupvar (value value) ...)]
           [/CREATE ['label' | DEFAULT ...] VAC | VPC | VAC VPC (var var) ...]
           [/TITLE='text'] [/FOOTNOTE='text'] [/HIDESMALLCOUNTS [COUNT=5]].

cell: as on MEANS; DEFAULT (SUM COUNT MEAN STDDEV SPCT NPCT) when CELLS is left out, ALL for every cell. The summary variables must be numeric. A Case Processing Summary has a row per summary variable and group combination; one OLAP Cubes table per combination of grouping variables (one from each BY) nests the categories of the first one outermost, each level with a Total, and gives a row per summary variable. GAC adds a row per pair of categories of one grouping variable with every statistic of the second minus that of the first; GPC the same change as a percentage of the first. VAC and VPC do the same between two summary variables in every group. Labels name the differences in order (each pair gives its types in the order written); DEFAULT keeps the generated name. A case counts for a summary variable when it is valid on it and on the grouping variables of the table. HIDESMALLCOUNTS shows counts below n (from 2, default 5) as <n. TITLE and FOOTNOTE: one line per quoted string, \n breaks a line.

A subcommand given twice: the last one counts. Weighted when a weight variable is set.

Example

OLAP CUBES revenue cost BY year BY store /CELLS=SUM MEAN COUNT
  /CREATE 'Growth' DEFAULT GAC GPC (year (2024 2025)) /TITLE='Store results'.

statscraft help OLAP CUBES prints the same text in the terminal. All commands

Statscraft 0.61.0, release v0.61.0

CODEBOOK

Dictionary entries and summary statistics of variables and multiple response sets.

Syntax

CODEBOOK [varlist] [$set ...] [$ALL]
         [/VARINFO=POSITION LABEL TYPE FORMAT MEASURE ROLE ATTRIBUTES VALUELABELS MISSING
                   RESERVEDATTRIBUTES]
         [/FILEINFO=NAME LOCATION CASECOUNT LABEL ATTRIBUTES DOCUMENTS WEIGHT RESERVEDATTRIBUTES]
         [/STATISTICS=COUNT PERCENT MEAN STDDEV QUARTILES | NONE]
         [/OPTIONS [MAXCATS=200] [VARORDER=FILE | ALPHA | VARLIST | MEASURE | ATTRIBUTE(name)]
                   [SORT=ASCENDING | DESCENDING]].

One table per variable and set; without a list every variable in file order, then every set.

[N], [O] or [S] right after a name (after a TO list: its last variable) sets the level that decides its statistics, not the level shown; strings and sets cannot be [S]. Nominal and ordinal variables and sets get the count and percent of every value (each labeled value and each value found), scale variables the mean, standard deviation and quartiles plus counts of their labeled values. An unknown level is guessed from the values. Percents are of every case the filter keeps, missing ones included; a set’s can add up to more than 100. Above MAXCATS values (scale: labeled values) the values, labels and counts are left out. VARINFO left out means all but RESERVEDATTRIBUTES; ATTRIBUTES shows custom attributes, RESERVEDATTRIBUTES those starting with $ (both skip names starting with @ or $@). FILEINFO adds a table about the file; NAME and LOCATION come from the GET FILE or SAVE that last read or wrote it in this run.

VARORDER: ALPHA by name; MEASURE nominal, ordinal, scale, unknown; ATTRIBUTE(name) by the attribute’s value, those without it first, then those with an empty one. VARLIST is the default with a list. Every variable or set may be named once. SPLIT FILE is ignored; FILTER and the weight apply.

Example

CODEBOOK region income [O] $media /VARINFO=LABEL MEASURE VALUELABELS
  /STATISTICS=COUNT MEAN /OPTIONS MAXCATS=12 VARORDER=ALPHA.

statscraft help CODEBOOK prints the same text in the terminal. All commands

Statscraft 0.61.0, release v0.61.0

VALIDATEDATA

Find suspicious variables, incomplete or duplicate IDs, empty cases and rule violations.

Syntax

VALIDATEDATA [VARIABLES=varlist] [ID=varlist] [CROSSVARRULES=$VD.CRule[n] ... | n ... | ALL]
  [/VARCHECKS [STATUS=ON | OFF] [PCTMISSING=70] [PCTEQUAL=95] [PCTUNEQUAL=90] [CV=0.001]
              [STDDEV=0]]
  [/IDCHECKS [INCOMPLETE] [DUPLICATE] | NONE]
  [/CASECHECKS [REPORTEMPTY=YES | NO] [SCOPE=ANALYSISVARS | ALLVARS]]
  [/RULESUMMARIES [BYVARIABLE] [BYRULE] | NONE]
  [/CASEREPORT [DISPLAY=YES | NO] [MINVIOLATIONS=1] [CASELIMIT=FIRSTN(500) | NONE]]
  [/SAVE [EMPTYCASE[(name)]] [INCOMPLETEID[(name)]] [DUPLICATEID[(name)]]
         [RULEVIOLATIONS[(name)]]].

Give at least one of VARIABLES (analysis variables), ID (the variables that together identify a case) and CROSSVARRULES. Keywords are written in full; a subcommand may come once and may not be empty. VARCHECKS lists analysis variables with more missing values than PCTMISSING percent of the cases; nominal and ordinal ones (strings too) whose largest category holds more than PCTEQUAL percent of the valid values, or whose categories have one case each in more than PCTUNEQUAL percent of them; scale ones whose absolute coefficient of variation is below CV (0 turns it off; skipped when the mean is 0) or whose standard deviation is below STDDEV. A variable of unknown level gets one from its values. IDCHECKS lists the cases whose ID has a missing or blank part and the groups of cases that share a complete ID. CASECHECKS lists empty cases: every analysis variable (SCOPE=ALLVARS: every variable but the ID, split and rule outcome variables) missing or blank.

Rules live in the dictionary. A single-variable rule is the data file attribute $VD.SRule[n], a text of Name=‘value’ properties separated by commas, among them Label and Type (Numeric, String or Date); an analysis variable links to it with the variable attribute $VD.SRuleRef[n] holding Rule=‘$VD.SRule[n]’ and OutcomeVar=‘name’. A cross-variable rule is $VD.CRule[n] with Label, Expression and OutcomeVar. The outcome variable, made beforehand with COMPUTE, is 1 for a case that breaks the rule; mark it with the variable attribute $VD.RuleOutcomeVar(‘Yes’) so the variable lists skip it. Broken or unknown rules and links are skipped with a warning; one outcome variable used by two rules is an error. RULESUMMARIES counts single-variable violations by variable (default) or by rule; cross-variable rules are always counted per rule. CASEREPORT lists the cases with at least MINVIOLATIONS violations, the first 500 by default. SAVE adds EmptyCase, IncompleteID (1 or 0), DuplicateIDGroup (the same number for cases sharing an ID, else 0) and ValidationRuleViolations (the count per case); a default name in use gets _1, _2 and so on, a given name in use is an error. Missing means user- or system-missing. Works within SPLIT FILE groups and on the cases FILTER keeps; the weight is ignored with a warning.

Example

VALIDATEDATA VARIABLES=age income visits ID=household member
  /VARCHECKS PCTMISSING=40 CV=0.01 /SAVE DUPLICATEID(dupgroup) EMPTYCASE.

statscraft help VALIDATEDATA prints the same text in the terminal. All commands

Statscraft 0.61.0, release v0.61.0

T-TEST

One-sample, independent-samples and paired-samples t tests with effect sizes.

Syntax

T-TEST /TESTVAL=value /VARIABLES=varlist
T-TEST /GROUPS=var[(value) | (value, value)] /VARIABLES=varlist
T-TEST /PAIRS=varlist [WITH varlist [(PAIRED)]] [/varlist ...]
       [/CRITERIA=CI(0.95)] [/MISSING=ANALYSIS | LISTWISE [INCLUDE]]
       [/ES DISPLAY(TRUE | FALSE) STANDARDIZER(SD | CORRECTED_SD | AVERAGE)].

GROUPS without values compares 1 with 2; one value splits at it (at or above against below).

The independent test shows Levene’s test and rows for equal and unequal variances. PAIRS without WITH pairs every variable with every later one; WITH pairs each left with each right one, and (PAIRED) the n-th with the n-th. ANALYSIS (default) leaves out cases missing in each analysis, LISTWISE those missing on any variable of the test type. Effect sizes: Cohen’s d and Hedges’ correction (and Glass’s delta for groups) with confidence intervals; they use weights rounded to whole numbers. Weighted when a weight variable is set.

Example

GET FILE='survey.sav'.
T-TEST GROUPS=contacted(0, 1) /VARIABLES=satisfaction spend.
T-TEST /TESTVAL=40 /VARIABLES=spend.
T-TEST GROUPS=gender(1, 2) /VARIABLES=age /CRITERIA=CI(0.99).

The example reads the sample data file survey.sav, an invented customer survey; save it in the folder you run the syntax from.

Example output

Group Statistics

NMeanStd. DeviationStd. Error Mean
Overall satisfaction with the serviceNo1443.131.020.08
Yes1333.181.310.11
Monthly spend in eurosNo14639.4014.011.16
Yes13837.5612.301.05

statscraft help T-TEST prints the same text in the terminal. All commands

Statscraft 0.61.0, release v0.61.0

ONEWAY

One-way analysis of variance with contrasts and post hoc comparisons.

Syntax

ONEWAY deps BY factor [/STATISTICS=DESCRIPTIVES EFFECTS HOMOGENEITY WELCH BROWNFORSYTHE ALL NONE]
       [/CONTRAST=coefficients] [/POLYNOMIAL=degree] [/POSTHOC=test ... [ALPHA(0.05)]]
       [/RANGES=LSD | DUNCAN | SNK | TUKEYB | TUKEY | MODLSD | SCHEFFE [(alpha)]] ...
       [/MISSING=ANALYSIS | LISTWISE [INCLUDE | EXCLUDE]] [/CRITERIA=CILEVEL(0.95)] [/PLOT MEANS]
       [/TEMPLATE='file']
       [/MATRIX=IN(file | dataset | *) | OUT(file | dataset | *) | NONE].

test: LSD BONFERRONI SIDAK TUKEY SCHEFFE GT2 GABRIEL GH T2 T3 C (pairwise comparisons), DUNNETT DUNNETTL DUNNETTR [(refcat)] (each group against the reference group, by default the last; L: smaller, R: larger), SNK BTUKEY DUNCAN FREGW QREGW WALLER[(kratio)] (homogeneous subsets only); TUKEY SCHEFFE GT2 GABRIEL give both. DUNCAN and the Dunnett keywords are written in full. Every value of the factor is a group. CONTRAST gives one coefficient per group in ascending order (n*c repeats c n times); it is tested with pooled and separate variances. HOMOGENEITY gives Levene’s test four ways, one row each under Based on Mean, Median, Median and with adjusted df, and trimmed mean. Multiple Comparisons show every ordered pair of groups (Dunnett C has no significance).

Homogeneous subsets use the harmonic mean of the group sizes (the R-E-G-W tests the sizes themselves); Tukey B and WALLER show no significance. WALLER, the Waller-Duncan t test, takes the ratio of the seriousness of a Type 1 to a Type 2 error as a whole number above 1 (100 by default); it calls two means different when they are t_B s sqrt(2/n) apart, t_B the Bayesian t value from the k-ratio, the F ratio of the analysis of variance and its df, n the harmonic mean of the group sizes. Weighted when a weight variable is set. PLOT MEANS gives each dependent a line chart through the mean of every group, as chart data.

POLYNOMIAL (1 to 5, the last one given counts; lowered with a warning to the groups minus 1) splits the between-groups sum of squares into trend terms in the ANOVA table, with the group value as the metric: a Weighted row per degree (sequential, the groups weighted by size) and a Deviation row of what is left (none after the last possible degree); when the group sizes differ and the groups are equally spaced there is also an Unweighted row per degree.

RANGES names one of these post hoc tests (MODLSD, also LSDMOD, is Bonferroni), at most 10 times; its tests add to those of POSTHOC and the last alpha given anywhere counts for all of them.

EFFECTS adds the rows Fixed Effects (pooled standard deviation, and the error and interval of the overall mean from the within mean square) and Random Effects (error and interval from the between-groups component, which has its own column) to the Descriptives table; without DESCRIPTIVES it holds only those two rows. A negative component counts as 0 in the error, with a warning.

MATRIX=OUT writes, per split group and value of the factor, the records MEAN, STDDEV and N of every dependent; IN reads such records (and the pooled MSE and DFE records, which then give the within variance) and runs everything that needs no cases: HOMOGENEITY is an error, and the minimum and maximum of the descriptives are empty. TEMPLATE is ignored; charts come as data.

Example

GET FILE='survey.sav'.
ONEWAY satisfaction BY region.
ONEWAY spend BY age_group /STATISTICS=DESCRIPTIVES HOMOGENEITY.
ONEWAY satisfaction BY region /POSTHOC=TUKEY ALPHA(0.05).

The example reads the sample data file survey.sav, an invented customer survey; save it in the folder you run the syntax from.

Example output

ANOVA

Sum of SquaresdfMean SquareFSig.
Overall satisfaction with the serviceBetween Groups47.20315.7313.130.00
Within Groups327.122731.20
Total374.32276

statscraft help ONEWAY prints the same text in the terminal. All commands

Statscraft 0.61.0, release v0.61.0

CORRELATIONS

Pearson correlations with significance and case counts.

Syntax

CORRELATIONS [/VARIABLES=]varlist [WITH varlist] [/varlist ...]
             [/PRINT=TWOTAIL | ONETAIL  SIG | NOSIG  FULL | LOWER | LNODIAG]
             [/STATISTICS=DESCRIPTIVES XPROD ALL] [/MISSING=PAIRWISE | LISTWISE [INCLUDE]]
             [/MATRIX=OUT(* | 'file' | dataset)] [/CI [METHOD=FISHER] [BIAS=FALSE | TRUE] [CILEVEL=95]].

CI adds two rows to each coefficient, its lower and upper limit: Fisher’s transformation with the standard error 1 / sqrt(W - 3) (W the sum of the weights of the pair, above 3), BIAS=TRUE subtracting r / (2 (W - 1)) from the transformed value first; with ONETAIL one bound is -1 or 1 (the lower limit for a positive r, the upper for a negative or zero r) and the other is found at the one-tailed level.

MATRIX writes the last list without WITH as a matrix data file (ROWTYPE_ MEAN, STDDEV, N and CORR, VARNAME_; N is one record under LISTWISE, a record per variable under PAIRWISE unless every pair has the same count; one set per SPLIT FILE group); the tables are still shown, and with * the file replaces the active dataset. When every list has WITH, nothing is written and a warning says so.

A list alone gives a square matrix, WITH a rectangular one (left variables in rows). NOSIG marks coefficients significant at 0.05 with * and at 0.01 with **. XPROD adds cross-products and covariances; DESCRIPTIVES a table of means, standard deviations and counts. PAIRWISE (default) uses the cases valid on both variables of a pair; LISTWISE the cases valid on every variable of every list. Weighted when a weight variable is set.

Example

GET FILE='survey.sav'.
CORRELATIONS /VARIABLES=age spend satisfaction.
CORRELATIONS /VARIABLES=age spend WITH satisfaction /PRINT=ONETAIL NOSIG.
CORRELATIONS /VARIABLES=age spend satisfaction /MISSING=LISTWISE /STATISTICS=DESCRIPTIVES.

The example reads the sample data file survey.sav, an invented customer survey; save it in the folder you run the syntax from.

Example output

Correlations

Age in yearsMonthly spend in eurosOverall satisfaction with the service
Age in yearsPearson Correlation1-0.14-0.14
Sig. (2-tailed)0.020.02
N300284277
Monthly spend in eurosPearson Correlation-0.141-0.16
Sig. (2-tailed)0.020.01
N284284261
Overall satisfaction with the servicePearson Correlation-0.14-0.161
Sig. (2-tailed)0.020.01
N277261277

statscraft help CORRELATIONS prints the same text in the terminal. All commands

Statscraft 0.61.0, release v0.61.0

NONPAR CORR

Spearman’s rho and Kendall’s tau-b rank correlations with significance.

Syntax

NONPAR CORR [/VARIABLES=]varlist [WITH varlist] [/varlist ...]
            [/PRINT=SPEARMAN | KENDALL | BOTH  TWOTAIL | ONETAIL  SIG | NOSIG
                    FULL | LOWER | LNODIAG] [/MISSING=PAIRWISE | LISTWISE [INCLUDE]] [/SAMPLE]
            [/MATRIX=OUT(* | 'file' | dataset)] [/CI [METHOD(FHP | CC | BW)] [CILEVEL(95)]].

CI adds the lower and upper limit of Spearman’s rho (not of tau-b, which gets a warning): Fisher’s transformation with the standard error sqrt(1.06 / (W - 3)) (FHP, the default), or sqrt(1 / (W - 2) + |z| / (6 W + 4 sqrt(W))) (CC) or sqrt((1 + rho^2 / 2) / (W - 3)) (BW), z the transformed rho and W the sum of the weights of the pair; ONETAIL gives a bound as in CORRELATIONS.

MATRIX writes the last list without WITH: the records N (as in CORRELATIONS) and RHO, or TAUB when only KENDALL is asked (BOTH writes rho alone), with VARNAME_ and one set per SPLIT FILE group.

A list alone gives a square matrix, WITH a rectangular one (left variables in rows). Ties get their average rank; rho is tested with t on N - 2 df, tau-b with the normal approximation and the tie-corrected variance. NOSIG marks coefficients significant at 0.05 with * and at 0.01 with **. PAIRWISE (default) uses the cases valid on both variables of a pair; LISTWISE the cases valid on every variable of the list, each list on its own. A weight variable repeats each case as often as its weight rounded to a whole number. SAMPLE changes nothing.

Example

NONPAR CORR /VARIABLES=satisfaction recommend WITH age /PRINT=BOTH NOSIG.

statscraft help NONPAR CORR prints the same text in the terminal. All commands

Statscraft 0.61.0, release v0.61.0

PARTIAL CORR

Partial correlations of variables controlling for others, with significance.

Syntax

PARTIAL CORR [VARIABLES=]varlist [WITH varlist] BY controls [(order ...)] [/...]
             [/SIGNIFICANCE=TWOTAIL | ONETAIL] [/STATISTICS=NONE CORR DESCRIPTIVES BADCORR ALL]
             [/FORMAT=MATRIX | CONDENSED | SERIAL] [/MISSING=LISTWISE | ANALYSIS  EXCLUDE | INCLUDE]
             [/MATRIX=[IN(file | dataset | *)] [OUT(file | dataset | *)]].

A list alone gives a square matrix, WITH a rectangular one. Without orders the partials control for every control variable at once; an order k gives one block per set of k controls (up to five orders, 25 lists). Coefficients come from the zero-order Pearson correlations step by step, and are tested with t on M - k - 2 df, M the smallest weighted count of the correlations used. A coefficient that cannot be computed is empty. CORR shows the zero-order correlations first, BADCORR only when one of them is empty; DESCRIPTIVES the mean, standard deviation and N. CONDENSED shows the coefficients alone, marked * at 0.05 and ** at 0.01; SERIAL shows each pair once. LISTWISE (default) uses the cases valid on every variable of the list, controls included; ANALYSIS each pair’s valid cases. Weighted when a weight variable is set. MATRIX=OUT writes, for the first list, the records MEAN, STDDEV, N (one record, or a record per variable when pairwise counts differ) and PCORR of its variables, controlling for all controls (or the first order’s first set of controls), per split group; IN reads the CORR records of a file (REGRESSION and CORRELATIONS-type matrices) and needs N.

Example

PARTIAL CORR /VARIABLES=satisfaction recommend BY age /STATISTICS=CORR /SIGNIFICANCE=ONETAIL.

statscraft help PARTIAL CORR prints the same text in the terminal. All commands

Statscraft 0.61.0, release v0.61.0

NPAR TESTS

Nonparametric tests: one-sample, two and k related samples, two and k independent samples.

Syntax

NPAR TESTS [/CHISQUARE=varlist [(lo,hi)] [/EXPECTED=EQUAL | f1, n*f2, ...]]
           [/BINOMIAL[(p)]=varlist[(cut) | (value1,value2)]] [/RUNS(MEAN | MEDIAN | MODE | value)=varlist]
           [/K-S(NORMAL [mean,sd] | UNIFORM [min,max] | POISSON [mean] | EXPONENTIAL [mean])=varlist]
           [/WILCOXON | /SIGN | /MCNEMAR | /MH=varlist [WITH varlist [(PAIRED)]]]
           [/FRIEDMAN | /KENDALL | /COCHRAN=varlist]
           [/M-W | /K-S | /W-W | /MOSES[(n)] | /K-W | /J-T | /MEDIAN[(value)]=varlist BY var(value1,value2)]
           [/STATISTICS=[DESCRIPTIVES] [QUARTILES] [ALL]] [/MISSING=ANALYSIS | LISTWISE [INCLUDE]]
           [/METHOD=EXACT [TIMER(n)] | MC [CIN(n)] [SAMPLES(n)]] [/SAMPLE]
           [/KS_SIM [CIN(level)] [SAMPLES(n)] [NONORMAL]].

Long names work too: CHI-SQUARE, KOLMOGOROV-SMIRNOV, MANN-WHITNEY, WALD-WOLFOWITZ, KRUSKAL-WALLIS, JONCKHEERE-TERPSTRA. Without WITH every variable is paired with every later one; (PAIRED) pairs the n-th with the n-th. M-W, two-sample K-S, W-W and MOSES compare the two groups (MOSES: the first is the control group); K-W and J-T take every value from value1 to value2 as a group; MEDIAN does so when value1 < value2, and compares the two values otherwise. Exact significance where the method gives it for small samples: binomial; sign and McNemar up to 25 changes; Mann-Whitney when n1 n2 <= 400 and n1 n2 / 2 + min(n1, n2) <= 220; median test up to 30 cases (Fisher); W-W up to 30 cases; Moses.

K-S with normal parameters taken from the data uses the Lilliefors significance. A one-sample K-S against a normal, uniform or exponential distribution fitted to the data also gets a Monte Carlo significance with its interval: SAMPLES samples (10000) of the fitted distribution, the parameters estimated again in each, each test starting at the SET SEED value; KS_SIM sets SAMPLES and the level CIN (99), and NONORMAL leaves the normal out. Past 200,000,000 draws (cases times samples) a warning replaces it. METHOD adds exact significances for Wilcoxon, sign, McNemar, Mann-Whitney and the runs tests (MC gives them too, as exact results replace simulated ones), for the two-sample K-S (every assignment of the cases to the groups), the median test of several groups (every split of the cases above the median), Kruskal-Wallis and Jonckheere-Terpstra (every labelling of the cases), marginal homogeneity (each case off the diagonal puts either value of its pair first) and for Friedman, Kendall and Cochran (every arrangement of each case’s values over the columns, as Exact Sig. and Point Probability; too large a problem keeps the asymptotic one with a warning), for CHISQUARE (every way the cases can fall in the categories), the median test of two groups past 30 cases (Fisher) and the one-sample K-S against a normal, uniform or exponential distribution whose parameters are given (the exact distribution of the largest difference); a one-sample K-S against the Poisson or with parameters from the data keeps the asymptotic significance, with a warning. ANALYSIS (default) leaves out cases missing on a test’s variables, LISTWISE cases missing on any variable of the command.

A weight repeats each case as often as its weight rounded to a whole number. SAMPLE changes nothing.

Example

NPAR TESTS /M-W=income BY gender(1,2) /WILCOXON=before WITH after /STATISTICS=QUARTILES.

statscraft help NPAR TESTS prints the same text in the terminal. All commands

Statscraft 0.61.0, release v0.61.0

NPTESTS

Nonparametric tests picked by measurement level: one sample, independent samples, related samples.

Syntax

NPTESTS [/ONESAMPLE TEST(fields) [CHISQUARE[(EXPECTED=EQUAL | CUSTOM(FREQUENCIES=list CATEGORIES=list))]]
          [BINOMIAL[(TESTVALUE=p SUCCESSCATEGORICAL=FIRST | LIST(values)
                    SUCCESSCONTINUOUS=CUTPOINT(MIDPOINT | value) CLOPPERPEARSON JEFFREYS LIKELIHOOD)]]
          [KOLMOGOROV_SMIRNOV[(NSAMPLES=n MC_CILEVEL=level NORMAL=SAMPLE[(SIMULATION=TRUE | FALSE)] |
                    CUSTOM(MEAN=m SD=s) UNIFORM=SAMPLE | CUSTOM(MIN=a MAX=b)
                    EXPONENTIAL=SAMPLE | CUSTOM(MEAN=m) POISSON=CUSTOM(MEAN=m))]]
          [RUNS[(GROUPCATEGORICAL=SAMPLE | LIST(values)
                    GROUPCONTINUOUS=CUTPOINT(SAMPLEMEDIAN | SAMPLEMEAN | value))]]
          [WILCOXON(TESTVALUE=value)]]
        [/INDEPENDENT TEST(fields) GROUP(field) [MANN_WHITNEY] [WALD_WOLFOWITZ] [KOLMOGOROV_SMIRNOV]
          [HODGES_LEHMAN] [MOSES[(TRIMOUTLIERS=SAMPLE | n)]] [KRUSKAL_WALLIS[(COMPARE=c)]]
          [MEDIAN[(TESTVALUE=SAMPLE | value COMPARE=c)]] [JONCKHEERE_TERPSTRA[(ORDER=ASCENDING | DESCENDING
          COMPARE=c)]]]
        [/RELATED TEST(fields) [MCNEMAR[(SUCCESS=FIRST | LIST(values))]] [WILCOXON] [SIGN]
          [MARGINAL_HOMOGENEITY] [HODGES_LEHMAN] [COCHRAN[(SUCCESS=FIRST | LIST(values) COMPARE=c)]]
          [FRIEDMAN[(COMPARE=c)]] [KENDALL[(COMPARE=c)]]]
        [/MISSING [SCOPE=ANALYSIS | LISTWISE] [USERMISSING=EXCLUDE | INCLUDE]]
        [/CRITERIA [ALPHA=0.05] [CILEVEL=95] [SEED=2000000 | RANDOM]].

c is PAIRWISE (the default), STEPWISE or NONE. Keywords are written out in full and each appears once.

Nominal and ordinal fields count as categorical, scale fields as continuous; a field of unknown level gets one from its values. A test subcommand with only TEST (and GROUP) picks the tests itself: one sample, a binomial test for a categorical field with two values, chi-square for one with more, and a normal Kolmogorov-Smirnov test for a continuous field; independent samples, Mann-Whitney for two groups and Kruskal-Wallis for more; related samples, the fields split by level, then Wilcoxon (two) or Friedman (more) on continuous fields and McNemar (two) or Cochran (more) on categorical fields with two values between them. Named tests run only on fields that suit them, with a warning for the others: chi-square on categorical fields, K-S and Wilcoxon on continuous and ordinal ones; independent tests on continuous and ordinal fields, the two-group tests only when GROUP has two values (the lower value is the first group, the Moses control group); McNemar and Cochran on the nominal fields and on the ordinal fields separately; Wilcoxon, SIGN, HODGES_LEHMAN, FRIEDMAN and KENDALL on the continuous and ordinal fields together; MARGINAL_HOMOGENEITY on two ordinal fields.

FIRST makes the first value met in the data the success and needs exactly two values. A continuous field is cut at a point: values up to it are the success (binomial) or the first group (runs).

Binomial, sign and McNemar are exact up to 25 cases, Mann-Whitney for small groups, Wald-Wolfowitz up to 30 cases, the median test of two groups up to 30 cases (Fisher), Moses always. K-S with parameters from the data draws NSAMPLES samples (default 1000) from SEED for a Monte Carlo significance with a MC_CILEVEL interval; NORMAL=SAMPLE(SIMULATION=FALSE) uses the Lilliefors table, whose “>0.200” makes no decision at an ALPHA above 0.2.

Jonckheere-Terpstra decides one-sided in the ORDER direction. After a rejected test of three or more samples, COMPARE gives pairwise comparisons (Bonferroni-adjusted) or homogeneous subsets found by stepwise step-down tests. Output: the hypothesis test summary (ALPHA), a confidence interval summary (binomial intervals and Hodges-Lehmann estimates at CILEVEL), a detail table per test and the comparisons. USERMISSING applies to categorical fields; SCOPE=LISTWISE drops a case missing on any field named. Weights are rounded to whole numbers; the weight variable cannot be tested.

Example

NPTESTS /ONESAMPLE TEST(score rating) /INDEPENDENT TEST(score) GROUP(site) KRUSKAL_WALLIS(COMPARE=STEPWISE) /CRITERIA ALPHA=0.01.

statscraft help NPTESTS prints the same text in the terminal. All commands

Statscraft 0.61.0, release v0.61.0

PROPORTIONS

Tests and confidence intervals for a proportion or a difference of two proportions.

Syntax

PROPORTIONS /ONESAMPLE varlist [TESTVAL=0.5] [TESTTYPES=type ...] [CITYPES=type ...]
PROPORTIONS /PAIREDSAMPLES varlist [WITH varlist [(PAIRED)]] [TESTTYPES=...] [CITYPES=...]
PROPORTIONS /INDEPENDENTSAMPLES varlist BY var [SELECT=LEVEL(1, 2) | MIDPOINT | CUTPOINT(value)]
            [TESTTYPES=...] [CITYPES=...]
            [/SUCCESSVALUE=LAST | FIRST | LEVEL(values) | MIDPOINT | CUTPOINT(value)]
            [/MISSING [SCOPE=ANALYSIS | LISTWISE] [USERMISSING=EXCLUDE | INCLUDE]] [/CRITERIA CILEVEL=95].

One analysis per command. Tests, defaults marked *: one sample EXACT MIDP* SCORE* SCORECC WALD WALDCC; paired EXACT MIDP* MCNEMAR* MCNEMARCC WALD WALDCC; independent HAUCK_ANDERSON WALD WALDCC WALDH0* WALDH0CC. Intervals: one sample AGRESTI_COULL* ANSCOMBE CLOPPER_PEARSON JEFFREYS* LOGIT WALD WALDCC WILSON_SCORE* WILSON_SCORECC; paired AGRESTI_MIN BONETT_PRICE* NEWCOMBE* WALD WALDCC; independent AGRESTI_CAFFO* BROWN_LI_JEFFREYS HAUCK_ANDERSON NEWCOMBE* NEWCOMBECC WALD WALDCC. NONE turns tests or intervals off. TESTVAL, SELECT, TESTTYPES and CITYPES may also be written as subcommands. A case is a success when its value is the highest (LAST) or lowest (FIRST) valid value the analysis sees, one of the LEVEL values, no less than (lowest + highest) / 2 (MIDPOINT) or no less than the cut point; every other valid value is a failure. Groups: the two SELECT values, or the cases below the middle of the grouping variable’s range or below the cut point as group 1 and the rest as group 2; without SELECT the grouping variable is numeric with groups 1 and 2. A paired list without WITH pairs every variable with every later one; WITH pairs every left with every right variable, (PAIRED) the n-th with the n-th. ANALYSIS drops a case per analysis, LISTWISE drops it from all when any variable named is missing. Weights count as frequencies; exact and mid-p probabilities use the counts rounded to whole numbers. Bounds are kept within 0 to 1 (-1 to 1 for differences).

Two-sided p values are twice the smaller tail, at most 1. CILEVEL is a percent; a value below 1 is read as a fraction.

Example

PROPORTIONS /INDEPENDENTSAMPLES passed BY school SELECT=LEVEL('north', 'south')
  TESTTYPES=WALDH0 HAUCK_ANDERSON CITYPES=NEWCOMBE WALD /CRITERIA CILEVEL=90.

statscraft help PROPORTIONS prints the same text in the terminal. All commands

Statscraft 0.61.0, release v0.61.0

EXAMINE

Descriptives, percentiles, M-estimators, extreme values and normality tests, by factor cells.

Syntax

EXAMINE [VARIABLES=]deps [BY factor [BY factor] [factor ...]] [/TOTAL | NOTOTAL] [/ID=var]
        [/PERCENTILES[(list)][=HAVERAGE | WAVERAGE | ROUND | EMPIRICAL | AEMPIRICAL | NONE]]
        [/STATISTICS=DESCRIPTIVES EXTREME[(n)] ALL NONE] [/CINTERVAL=95]
        [/MESTIMATORS[=HUBER[(c)] TUKEY[(c)] HAMPEL[(a,b,c)] ANDREW[(c)] ALL NONE]]
        [/PLOT=[BOXPLOT] [STEMLEAF] [HISTOGRAM] [NPPLOT] [SPREADLEVEL[(power)]] | ALL | NONE]
        [/COMPARE=GROUPS | VARIABLES]
        [/MISSING=LISTWISE | PAIRWISE  EXCLUDE | INCLUDE  NOREPORT | REPORT].

Each dependent is analyzed over all cases (unless NOTOTAL) and in every cell of each factor term, two factors crossed with BY. Descriptives (the default): mean with its confidence interval (CINTERVAL, 50 to 99.99), 5% trimmed mean, median, variance, standard deviation, minimum, maximum, range, interquartile range, skewness and kurtosis with standard errors. PERCENTILES alone gives 5 10 25 50 75 90 95 by HAVERAGE, with Tukey’s hinges when 25, 50 or 75 is listed; the method also gives the median and the interquartile range. MESTIMATORS alone gives all four (Huber 1.339, Tukey 4.685, Hampel 1.7 3.4 8.5, Andrews 1.34 times pi), each started at the median and scaled by the median absolute deviation. EXTREME lists the n highest and lowest values by case number or by the ID variable.

NPPLOT gives the Tests of Normality table (Kolmogorov-Smirnov with the Lilliefors significance and Shapiro-Wilk by Royston’s algorithm, 3 to 5000 cases).

Plots come as chart data (a data table, and Vega-Lite with –vega-lite). Without PLOT every cell gets a stem-and-leaf plot and a boxplot; a PLOT subcommand names the ones wanted. BOXPLOT: the box spans Tukey’s hinges around the median; a case 1.5 to 3 box lengths past a hinge is an outlier, 3 or more an extreme, each labeled by case number or by the ID variable, and the whiskers stop at the last unmarked values. COMPARE=GROUPS (default) gives each dependent one plot with a box per cell; VARIABLES puts all dependents in one plot, grouped by cell. STEMLEAF lists the cases past the outlier bounds as extremes. NPPLOT adds the normal Q-Q plot (each distinct value against the normal score of its mean rank over W + 1) and the detrended one. SPREADLEVEL needs a factor: per cell the log of the interquartile range against the log of the median, with the slope and the power it suggests (1 minus the slope); with a power p the values are raised to p first (0 takes logs), and the Test of Homogeneity of Variance table gives Levene’s tests on the same values. ALL is every plot.

LISTWISE (default) leaves out a case missing on any dependent or factor, PAIRWISE only from the analyses of that variable. INCLUDE makes user-missing values of the dependents valid, REPORT makes missing values of the factors categories. Weighted when a weight variable is set (Shapiro-Wilk rounds the weights and takes 3 to 50 cases with non-integer weights).

Example

EXAMINE VARIABLES=income BY region /PERCENTILES(25,50,75)=HAVERAGE /STATISTICS=ALL /MESTIMATORS /PLOT=NPPLOT.

statscraft help EXAMINE prints the same text in the terminal. All commands

Statscraft 0.61.0, release v0.61.0

REGRESSION

Linear regression with forced entry or removal and stepwise selection, residuals and diagnostics.

Syntax

REGRESSION [MATRIX=[IN(file | dataset | *)] [OUT(file | dataset | *)]]
           [/VARIABLES=varlist | (COLLECT)] [/DESCRIPTIVES=[DEFAULTS MEAN STDDEV VARIANCE CORR SIG
           BADCORR COV XPROD N ALL NONE]] [/MISSING=LISTWISE | PAIRWISE | MEANSUBSTITUTION [INCLUDE]]
           [/SELECT=var EQ | NE | LT | LE | GT | GE value] [/REGWGT=var] [/STATISTICS=[DEFAULTS R ANOVA COEFF OUTS ZPP CHANGE CI[(95)] BCOV COLLIN TOL
           F SES XTX SELECTION LABEL ALL]] [/CRITERIA=[DEFAULTS PIN[(0.05)] | FIN[(3.84)] POUT[(0.10)] |
           FOUT[(2.71)] TOLERANCE[(0.0001)] MAXSTEPS(n) CIN[(95)]]] [/ORIGIN | NOORIGIN]
           /DEPENDENT=varlist /[METHOD=]ENTER [varlist] | REMOVE varlist | STEPWISE [varlist] |
           FORWARD [varlist] | BACKWARD [varlist] | TEST(varlist)(varlist)... [/METHOD=...]
           [/RESIDUALS=[DEFAULTS DURBIN OUTLIERS(tempvars) ID(var) HISTOGRAM NORMPROB]]
           [/CASEWISE=[DEFAULTS OUTLIERS(3) | ALL PLOT(tempvar) DEPENDENT tempvars]]
           [/SAVE=tempvar[(name)] ... [FITS]] [/SCATTERPLOT=(y, x) ...] [/PARTIALPLOT=[ALL | varlist]]
           [/OUTFILE=COVB('file' | dataset) | CORB('file' | dataset)].

tempvar: PRED RESID ZPRED ZRESID SRESID DRESID SDRESID ADJPRED SEPRED MAHAL COOK LEVER DFBETA SDBETA DFFIT SDFIT COVRATIO MCIN ICIN. One equation per dependent; each METHOD works on the equation the ones before it left, and each step is a model. ENTER takes the variables in order of tolerance; STEPWISE removes the weakest variable while its F-to-remove fails POUT, then enters the strongest that passes PIN; FORWARD only enters, BACKWARD only removes (entering its list first when the equation is empty). A variable enters only when it and the variables in the equation keep the TOLERANCE. Without keywords STATISTICS is R ANOVA COEFF OUTS and DESCRIPTIVES is MEAN STDDEV CORR.

The tables: Variables Entered/Removed, Model Summary (CHANGE, DURBIN, SELECTION add columns), ANOVA, Coefficients (CI, ZPP, TOL, COLLIN, SES, F add columns), Excluded Variables, Coefficient Correlations (BCOV), Collinearity Diagnostics (COLLIN), the swept correlation matrix (XTX), Residuals Statistics (with RESIDUALS, CASEWISE or a plot), Casewise Diagnostics and Outlier Statistics. LISTWISE (default) uses the cases valid on every variable; PAIRWISE builds the correlations pair by pair, with the smallest pair count as N; MEANSUBSTITUTION puts the mean in place of a missing value. SAVE adds variables named PRE_1, RES_1 and so on, or as given; DFBETA and SDBETA save one per coefficient (name0, name1, …), MCIN and ICIN a lower and an upper bound.

Weighted when a weight variable is set; REGWGT gives weighted least squares. Charts come as data: HISTOGRAM(tempvars) a histogram with a normal curve; NORMPROB(tempvars) a normal P-P plot (PRED, RESID and DRESID are plotted standardized); RESIDUALS alone gives both of ZRESID. SCATTERPLOT plots each pair, the first on the vertical axis; a temporary variable takes a star (*ZRESID).

PARTIALPLOT plots, for each independent (or those listed), the dependent’s residuals against the independent’s, both regressed on the other independents; it needs two in the equation. TEMPLATE is ignored with a warning. LABEL changes nothing (the tables show names or labels as SET TVARS says) and a warning says so. MAXSTEPS bounds the steps of all the FORWARD, BACKWARD and STEPWISE methods of an equation together. On CASEWISE, DEFAULTS keeps the dependent, PRED and RESID as columns and adds the temporary variables named with it; a list without DEFAULTS replaces them.

TEST enters every variable named in its sets together (Model Variables Entered/Removed says Test), then gives a Subset Tests table: for each set the change in R square when it leaves the equation, the change in the regression sum of squares, df, mean square and F (against the residual mean square of the full equation) with its significance, and a Residual row.

SELECT makes the correlation matrix, the equation and its tests from the cases where the condition holds (a missing value on the variable leaves the case out; the variable is not on VARIABLES, DEPENDENT or METHOD, and its value is quoted for a string variable). The other cases still get predictions, residuals, leverage, Mahalanobis and Cook’s distance; the residual statistics, the outlier lists and the plots are of the selected and the unselected cases apart (SEPARATE, the default) or of all of them (POOLED), Casewise Diagnostics list both with a Selected Status, and SAVE fills every case.

MATRIX must come first. OUT writes the records MEAN, STDDEV, N (one record, or a record per variable when pairwise counts differ) and CORR (OCORR with ORIGIN) of every variable on VARIABLES, per split group; * puts them in the active dataset. IN gives the equation from such records, which have no cases: SAVE, RESIDUALS, CASEWISE, the plots, SELECT and REGWGT are errors then.

OUTFILE (one dependent variable, not with MATRIX=OUT) writes a .sav file or a dataset made with DATASET DECLARE for the last equation: COVB the covariance matrix of the coefficients, CORB their correlation matrix, as RowType_ (COV or CORR), VarName_ and a column P1, P2, … for the constant (first, unless ORIGIN) and each independent in the order of the Coefficients table, with a record per coefficient and then the records EST, SE, SIG (the significance of t) and DF (the residual degrees of freedom), named by the dependent variable, per split group.

Example

GET FILE='survey.sav'.
REGRESSION /DEPENDENT=satisfaction /METHOD=ENTER age spend contacted.
REGRESSION /STATISTICS=COEFF R ANOVA CI(95) /DEPENDENT=spend /METHOD=ENTER age.
REGRESSION /DEPENDENT=satisfaction /METHOD=STEPWISE age spend contacted switching
  /SAVE PRED RESID.

The example reads the sample data file survey.sav, an invented customer survey; save it in the folder you run the syntax from.

Example output

Coefficients

ModelUnstandardized Coefficients / BUnstandardized Coefficients / Std. ErrorStandardized Coefficients / BetatSig.
1(Constant)4.340.3512.380.00
Age in years-0.010.01-0.16-2.630.01
Monthly spend in euros-0.020.01-0.18-2.900.00
Contacted customer support in the last year0.110.140.050.820.41

Dependent variable: Overall satisfaction with the service.

statscraft help REGRESSION prints the same text in the terminal. All commands

Statscraft 0.61.0, release v0.61.0

RELIABILITY

Reliability of a scale: Cronbach’s alpha, split-half and other models, item statistics and ICC.

Syntax

RELIABILITY /VARIABLES=varlist [/SCALE(label)=varlist | ALL]
            [/MODEL=ALPHA | OMEGA | SPLIT[(n)] | GUTTMAN | PARALLEL | STRICTPARALLEL]
            [/STATISTICS=DESCRIPTIVE SCALE CORR COV ANOVA [FRIEDMAN | COCHRAN] TUKEY HOTELLING ALL]
            [/SUMMARY=MEANS VARIANCE COV CORR TOTAL ALL]
            [/ICC=[MODEL(MIXED | RANDOM | ONEWAY)] [TYPE(CONSISTENCY | ABSOLUTE)] [CIN=95] [TESTVAL=0]]
            [/METHOD=COVARIANCE] [/MISSING=EXCLUDE | INCLUDE]
            [/MATRIX=[IN(file | dataset | *)] [OUT(file | dataset | *)] [NOPRINT]].

A case missing on any variable of VARIABLES is left out. ALPHA (default) gives Cronbach’s alpha and the alpha of the standardized items; OMEGA gives McDonald’s omega for one common factor, from the closed form built on the covariances (it needs 3 items; with SUMMARY TOTAL the last column of Item-Total Statistics is omega if the item is deleted, which needs 4); SPLIT puts n items (default half, the odd one in the first part) in the second part and gives the alpha of each part, the correlation between them, Spearman-Brown and Guttman’s split-half; GUTTMAN gives lambda 1 to 6; PARALLEL and STRICTPARALLEL give the maximum likelihood estimates and a chi-square test of the model. SUMMARY TOTAL is the Item-Total Statistics: scale mean, variance and alpha if the item is deleted and the corrected item-total correlation. ANOVA is the repeated measures table; FRIEDMAN (with Kendall’s W) and COCHRAN give their chi-square in place of F, computed from the values as they are (give ranks or 0/1 items); TUKEY adds the test for nonadditivity; HOTELLING tests that the item means are equal. ICC gives single and average measure coefficients with confidence intervals and F tests.

Items without variance are dropped, with a warning, when the model or a statistic needs the covariance matrix (all but ALPHA and SPLIT with DESCRIPTIVE, SCALE, ANOVA and TOTAL, and without ICC and MATRIX).

Weighted when a weight variable is set. MATRIX=OUT writes the records N, MEAN, STDDEV and CORR of the variables of VARIABLES, per split group, and shows the analysis unless NOPRINT is given; IN gives every statistic that needs no cases from such a file (all four records are required): Tukey’s test is an error then.

Example

RELIABILITY /VARIABLES=q1 TO q10 /SCALE('Satisfaction') ALL /MODEL=ALPHA /STATISTICS=DESCRIPTIVE SCALE /SUMMARY=TOTAL.

statscraft help RELIABILITY prints the same text in the terminal. All commands

Statscraft 0.61.0, release v0.61.0

WEIGHTED KAPPA

Cohen’s weighted kappa: how well two raters agree on an ordered scale.

Syntax

WEIGHTED KAPPA varlist | rowlist BY columnlist
               [/MISSING CLASSMISSING=TABLE | INCLUDE]
               [/CRITERIA [ASYMPTOTICCILEVEL=95] [WEIGHTING=LINEAR | QUADRATIC] [IGNORECASE=FALSE | TRUE]]
               [/PRINT [TABULATION(ALL | rowlist BY columnlist)] [CASE(UPPER | LOWER)]
                       [ORDER(ASCENDING | DESCENDING)]].

One list pairs each variable with every later one, the earlier as the row; two lists pair every row variable with every column variable, never a variable with itself. Both variables of a pair must be numeric, or both string. The k categories of a pair are the values either rater used, numbers by size and strings alphabetically, and two categories d places apart get the agreement weight 1 - d/(k - 1) (LINEAR) or 1 - d^2/(k - 1)^2 (QUADRATIC). Each pair drops the cases missing on either of its variables; INCLUDE keeps user-missing values, each as a category of its own.

The kappa table has a row per pair: N, the kappa, its asymptotic standard error, z with its two-sided significance (from the standard error under chance agreement) and the confidence interval at ASYMPTOTICCILEVEL percent. IGNORECASE=TRUE compares strings regardless of case and shows them in the case CASE names. TABULATION adds the table of counts of every pair, or of the pairs the two subsets make, its categories in ORDER. Case weights are rounded to whole numbers (0.5 or less drops the case). A pair with fewer than two cases or only one category is skipped with a warning. KEYWORD(value) works as KEYWORD=value; ASYMPTOTIC_CILEVEL and IGNORE_CASE are other spellings.

Example

WEIGHTED KAPPA nurse_a nurse_b BY doctor /CRITERIA WEIGHTING=QUADRATIC ASYMPTOTICCILEVEL=90
  /PRINT TABULATION(ALL).

statscraft help WEIGHTED KAPPA prints the same text in the terminal. All commands

Statscraft 0.61.0, release v0.61.0

FLEISS MULTIRATER KAPPA

Fleiss’ kappa: how well several raters agree when they sort subjects into categories.

Syntax

FLEISS MULTIRATER KAPPA [VARIABLES=]varlist
                        [/MISSING CLASSMISSING=EXCLUDE | INCLUDE]
                        [/CRITERIA [ASYMPTOTICCILEVEL=95] [IGNORECASE=FALSE | TRUE]]
                        [/PRINT [CATEGORY] [CASE(UPPER | LOWER)]].

Every variable is a rater and every case a subject; at least two raters, all numeric or all string, each named once. A case missing on any rater is dropped; INCLUDE keeps user-missing values as categories. Numeric ratings lose their fractions. The overall table gives the kappa, its asymptotic standard error under chance agreement, z with its two-sided significance and the confidence interval at ASYMPTOTICCILEVEL percent. CATEGORY adds a row per category: the conditional probability that a second rating of a subject falls in it when one did, its kappa and the same test. Case weights are rounded to whole numbers (0.5 or less drops the case). At least two subjects and two categories are needed. IGNORECASE and CASE work as on WEIGHTED KAPPA.

Example

FLEISS MULTIRATER KAPPA judge1 TO judge4 /PRINT CATEGORY /CRITERIA ASYMPTOTICCILEVEL=99.

statscraft help FLEISS MULTIRATER KAPPA prints the same text in the terminal. All commands

Statscraft 0.61.0, release v0.61.0

RATIO STATISTICS

Statistics of the ratio of two positive variables, overall and within groups.

Syntax

RATIO STATISTICS numerator WITH denominator [BY group [(ASCENDING | DESCENDING | NOSORT)]]
                 [/MISSING=EXCLUDE | INCLUDE] [/PRINT=statistic ...]
                 [/OUTFILE('file or dataset')=statistic ...].

statistic: MEAN MEDIAN WGTMEAN MIN MAX RANGE STDDEV AAD COD PRD MNCOV MDCOV CIN[(95)] BCOC((low, high) …) WCOC(percent …) A case counts when both variables are valid and above 0 and its weight, rounded to a whole number, is above 0. WGTMEAN is the sum of numerators over the sum of denominators, PRD the mean over WGTMEAN. AAD is the mean distance from the median and COD that in percent of the median; MNCOV is the standard deviation in percent of the mean, MDCOV the root mean square distance from the median (over N - 1) in percent of the median. BCOC is the percent of ratios from low to high, ends included; WCOC the percent within that many percent of the median. CIN adds intervals to MEAN and WGTMEAN (t with N - 1 df, a delta method variance for WGTMEAN) and to MEDIAN (from order statistics, with the actual coverage, at least the level asked). Without PRINT only the case processing summary shows. The groups may include a missing value. OUTFILE writes the overall record first, the group variable empty, then one record per group; it is not available under SPLIT FILE. A subcommand without content is ignored.

Example

RATIO STATISTICS rent WITH income BY district (DESCENDING)
  /PRINT=MEDIAN COD PRD WCOC(10 25) CIN(90).

statscraft help RATIO STATISTICS prints the same text in the terminal. All commands

Statscraft 0.61.0, release v0.61.0

BAYES ONESAMPLE

Bayesian inference on one mean, proportion or Poisson rate: Bayes factors and posteriors.

Syntax

BAYES ONESAMPLE /INFERENCE DISTRIBUTION=NORMAL | BINOMIAL | POISSON VARIABLES=varlist
                           [ANALYSIS=POSTERIOR | BAYESFACTOR | BOTH]
   [/DATA VARIABLES=sublist [VARIANCE=v] [NULLVALUE=0] [ALTERGVALUE=g]          (NORMAL)
         [SUCCESS=LAST | FIRST | MIDPOINT | CUTPOINT(v) | LEVEL(values)]    (BINOMIAL)
         [NULLPRIORPARAM=2 2] [ALTERPRIORPARAM=a b]] ...         (BINOMIAL, POISSON)
   [/PRIOR [VARDIST=DIFFUSE | INVCHISQ(df scale) | INVGAMMA(shape scale) | JEFFREYS2 | JEFFREYS4]
           [PRECDIST=GAMMA(shape rate) | CHISQ(df)] [MEANDIST=DIFFUSE | NORMAL(mean [variance])]
           [KAPPA=1] [TYPE=CONJUGATE(a b)]]
   [/CRITERIA [CILEVEL=95] [METHOD=AGL | MCA] [SEED=RANDOM | n] [TOL=0.000001] [MAXITER=2000]
              [MCSAMPLES=10000]] [/MISSING SCOPE=ANALYSIS | LISTWISE].

Each variable is analysed alone. A DATA subcommand sets its keywords for the variables of its sublist; the others keep the defaults. NORMAL: the Bayes factor BF01 weighs a mean of NULLVALUE against a normal spread of means around it. With a known VARIANCE the spread is g times that variance (g = ALTERGVALUE, default 1). Without it, a given g fixes the spread relative to the unknown variance, and no g puts a Cauchy prior on the effect size (the JZS factor), integrated by adaptive quadrature or, with METHOD=MCA, by MCSAMPLES draws. The posterior of the mean: from the variance prior with a flat mean prior (DIFFUSE, JEFFREYS2, JEFFREYS4), or a conjugate normal mean prior centered on the first value of MEANDIST=NORMAL with KAPPA prior observations (INVCHISQ, INVGAMMA, PRECDIST); a conjugate prior with MEANDIST=DIFFUSE falls back to VARDIST=DIFFUSE. With a known variance the mean prior is flat or NORMAL(mean variance). BINOMIAL: SUCCESS picks the values that count as a success (LAST and FIRST: the highest and lowest value present; MIDPOINT: from halfway between the smallest and largest value up; CUTPOINT: from the value up). BF01 compares a beta prior NULLPRIORPARAM with ALTERPRIORPARAM, and the posterior comes from the beta prior TYPE=CONJUGATE(a b) (both above 0, or 0 0). POISSON: the same with gamma priors of shape and rate; the values must be counts.

ALTERPRIORPARAM is needed for a Bayes factor and TYPE for a posterior of these two.

Credible intervals have equal tails. Case weights are rounded to whole numbers; a weight below 0.5 drops the case.

Example

BAYES ONESAMPLE /INFERENCE DISTRIBUTION=NORMAL VARIABLES=commute ANALYSIS=BOTH
  /DATA VARIABLES=commute NULLVALUE=30
  /PRIOR VARDIST=INVGAMMA(3 200) MEANDIST=NORMAL(28) KAPPA=4.

statscraft help BAYES ONESAMPLE prints the same text in the terminal. All commands

Statscraft 0.61.0, release v0.61.0

BAYES RELATED

Bayesian inference on the mean difference of paired measurements.

Syntax

BAYES RELATED /PAIR VARIABLES=first second [VARIANCE=v] [NULLVALUE=0] [ALTERGVALUE=g]
              [/PAIR ...] [/INFERENCE [ANALYSIS=POSTERIOR | BAYESFACTOR | BOTH]]
              [/PRIOR ...] [/CRITERIA ...] [/MISSING SCOPE=ANALYSIS | LISTWISE].

Each pair is analysed as one sample of differences, first minus second, with the rules of BAYES ONESAMPLE DISTRIBUTION=NORMAL: NULLVALUE is the difference tested, VARIANCE a known variance of the differences. PRIOR and CRITERIA take the keywords of BAYES ONESAMPLE except TYPE. LISTWISE drops a case missing on any variable of any pair.

Example

BAYES RELATED /PAIR VARIABLES=pulse_before pulse_after NULLVALUE=0
  /PAIR VARIABLES=grip_left grip_right /INFERENCE ANALYSIS=BAYESFACTOR.

statscraft help BAYES RELATED prints the same text in the terminal. All commands

Statscraft 0.61.0, release v0.61.0

BAYES INDEPENDENT

Bayesian comparison of the means of two independent groups.

Syntax

BAYES INDEPENDENT /INFERENCE VARIABLES=varlist GROUP=var
                             SELECT=LEVEL(a b) | MIDPOINT | CUTPOINT(v)
                             [ANALYSIS=POSTERIOR | BAYESFACTOR | BOTH] [DATAVAR=v1 v2]
   [/ESTBF COMPUTATION=ROUDER[(1)] | GONEN([0] variance) | HYPER[(-0.75)]]
   [/PRIOR [EQUALDATAVAR=FALSE | TRUE] [VARDIST=DIFFUSE | JEFFREYS | INVCHISQ(df scale)]
           [MEANDIST=DIFFUSE | NORMAL(mean1 mean2 variance1 variance2)]]
   [/CRITERIA [CILEVEL=95] [TOL=0.000001] [MAXITER=2000]] [/MISSING SCOPE=ANALYSIS | LISTWISE].

LEVEL takes the two values of GROUP that form group 1 and group 2; MIDPOINT (the middle of the range of GROUP) and CUTPOINT put values below the point in group 1 and the rest in group 2. The difference is group 2 minus group 1. Bayes factors use the pooled t: ROUDER gives BF01 for a Cauchy prior of that scale on the effect size, GONEN BF01 for a normal prior with that mean and variance, HYPER BF10 for a hyper-prior with parameter a (above -1, at most -0.5). The posterior of the difference: with DATAVAR (known variances) normal, from flat or NORMAL mean priors; else with EQUALDATAVAR=TRUE a t from VARDIST=JEFFREYS or INVCHISQ, and in all other cases the unequal-variances posterior of flat priors (each group needs more than five cases). Weights as on BAYES ONESAMPLE.

Example

BAYES INDEPENDENT /INFERENCE VARIABLES=yield GROUP=fertilizer SELECT=LEVEL(1 2)
  ANALYSIS=BOTH /ESTBF COMPUTATION=GONEN(0.5)
  /PRIOR EQUALDATAVAR=TRUE VARDIST=JEFFREYS.

statscraft help BAYES INDEPENDENT prints the same text in the terminal. All commands

Statscraft 0.61.0, release v0.61.0

BAYES CORRELATION

Bayesian inference on the Pearson correlation of every pair of variables.

Syntax

BAYES CORRELATION /INFERENCE VARIABLES=varlist [ANALYSIS=POSTERIOR | BAYESFACTOR | BOTH]
                             [CVALUE=0] [MAXPLOTS=10]
   [/ESTBF [TYPE=JZS | FRACTION[(0.5)]] [NULLVALUE=0]]
   [/CRITERIA [CILEVEL=95] [SEED=RANDOM | n] [TOL=0.0001] [MAXITER=2000] [MCSAMPLES=10000]
              [POSTSAMPLES=10000]] [/MISSING SCOPE=PAIRWISE | LISTWISE].

Every variable is paired with every later one. JZS gives BF01 of a zero correlation against the default prior of the linear model; FRACTION(b) the fractional Bayes factor BF01 of NULLVALUE, with the fraction b of the data training the prior (b times N must exceed 1). A correlation of 1 or -1 gets no Bayes factor. The posterior of rho is proportional to (1 - rho^2)^CVALUE times the approximate likelihood; its mode, mean, variance and highest-density interval are computed by quadrature, so SEED and POSTSAMPLES do not change them. Unless ANALYSIS=BAYESFACTOR, the first MAXPLOTS pairs get a chart of the prior, likelihood and posterior densities of rho as chart data. MCSAMPLES is accepted and not used. Weights as on BAYES ONESAMPLE.

Example

BAYES CORRELATION /INFERENCE VARIABLES=sleep_hours focus_score mood ANALYSIS=BOTH
  /ESTBF TYPE=FRACTION(0.4).

statscraft help BAYES CORRELATION prints the same text in the terminal. All commands

Statscraft 0.61.0, release v0.61.0

BAYES ANOVA

Bayesian one-way analysis of variance: a Bayes factor for the groups and posteriors of their means.

Syntax

BAYES ANOVA dependent BY factor
   [/INFERENCE ANALYSIS=POSTERIOR | BAYESFACTOR | BOTH]
   [/ESTBF COMPUTATION=JZS | ZELLNER(g) | HYPER[(3)] | ROUDER[(1)]]
   [/PRIOR [TYPE=REFERENCE | CONJUGATE] [SHAPEPARAM=a0] [SCALEPARAM=b0]
           [MEANVECTOR=values] [VMATRIX=IDENTITY | row1; row2; ...]]
   [/PLOT [MEANS=values] [ERRORVAR=FALSE | TRUE]] [/DESIGN REGWGT=var]
   [/CRITERIA [CILEVEL=95] [TOL=0.000001] [MAXITER=2000]].

Each value of the factor forms a group. BF10 compares the model with one mean per group against one common mean; it depends on N, the number of groups and R square. ZELLNER fixes g of the g-prior; JZS mixes g over an inverse gamma (1/2, N/2); ROUDER(s) uses the scale s in that mixture; HYPER(a), a above 2, uses the hyper-g prior. The posterior table gives each group mean and the error variance. REFERENCE is the flat prior 1/variance. CONJUGATE needs SHAPEPARAM and SCALEPARAM of an inverse gamma on the error variance and MEANVECTOR, one prior mean per group in ascending order of the factor; VMATRIX is the lower triangle of the prior matrix of the means (times the variance), rows ending in ‘;’; one that is not positive definite becomes the identity with a warning. PLOT draws the prior, the likelihood and the posterior of the listed group means and of the error variance as chart data. REGWGT multiplies the case weights in the sums of squares; cases with a regression weight of 0 or below are left out.

Example

BAYES ANOVA reaction_ms BY font_size
  /INFERENCE ANALYSIS=BOTH /ESTBF COMPUTATION=ROUDER(0.7) /PLOT MEANS=10 14.

statscraft help BAYES ANOVA prints the same text in the terminal. All commands

Statscraft 0.61.0, release v0.61.0

BAYES REGRESSION

Bayesian linear regression: a Bayes factor for the model, posteriors, predictions and F tests.

Syntax

BAYES REGRESSION dependent [BY factors] [WITH covariates]
   [/DESIGN [FACTORS=sublist] [COVARIATES=sublist] [REGWGT=var]]
   [/INFERENCE ANALYSIS=POSTERIOR | BAYESFACTOR | BOTH]
   [/ESTBF [COMPUTATION=JZS | ZELLNER(g) | HYPER[(3)] | ROUDER[(1)]] [COMPARE=NULL | FULL]]
   [/PRIOR ...as on BAYES ANOVA] [/PREDICT REGRESSORS=values]
   [/SAVE [MEANPRED[(name)]] [VARIANCE[(name)]] [MODE[(name)]] [CIMEANPREDL[(name)]]
          [CIMEANPREDU[(name)]]] [/OUTFILE PARAMETER='file']
   [/PLOT [COVARIATES=sublist] [FACTORS=sublist] [MAX_CATEGORY=2] [INTERCEPT=FALSE | TRUE]
          [ERRORVAR=FALSE | TRUE] [BAYESPRED=FALSE | TRUE]]
   [/FTEST [LABEL='text'] [VARIABLES=sublist] [INTERCEPT=FALSE | TRUE] [TESTVALUES=values]] ...
   [/CRITERIA [CILEVEL=95] [TOL=0.000001] [MAXITER=2000]].

The model holds an intercept, one indicator per category of each factor (ascending; the last is redundant and set to 0) and the covariates; DESIGN lists narrow it. BF10 weighs the model against the intercept alone with the g-priors of BAYES ANOVA. COMPARE=FULL adds a table that weighs each model without one factor or covariate, and the intercept alone, against the full model. The posterior table gives every parameter and the error variance; PRIOR works as on BAYES ANOVA, with MEANVECTOR holding one value per parameter, intercept first, redundant ones included. PREDICT takes one value per factor (a category) and per covariate, factors first, and gives the predictive distribution; SAVE writes its mean, variance, mode and credible bounds for every case with valid regressors (default names such as MEANPRED_1). Each FTEST tests whether the parameters of its variables (and the intercept) equal TESTVALUES, 0 by default. PLOT draws prior, likelihood and posterior as chart data: of covariates, of the first MAX_CATEGORY categories of factors, of the intercept, of the error variance, and the predictive density. OUTFILE is accepted and writes no file. Cases missing on any variable of the model are left out.

Example

BAYES REGRESSION bill_total BY table_zone WITH party_size
  /INFERENCE ANALYSIS=BOTH /ESTBF COMPARE=FULL
  /PREDICT REGRESSORS=2 4 /FTEST LABEL='zone' VARIABLES=table_zone.

statscraft help BAYES REGRESSION prints the same text in the terminal. All commands

Statscraft 0.61.0, release v0.61.0

BAYES REPEATED

Bayesian one-way repeated measures analysis: a Bayes factor and posteriors of the condition means.

Syntax

BAYES REPEATED varlist
   [/INFERENCE ANALYSIS=POSTERIOR | BAYESFACTOR | BOTH] [/ESTBF COMPUTATION=BIC | ROUDER]
   [/DESIGN REGWGT=var] [/PLOT MEANS=sublist]
   [/CRITERIA [CILEVEL=95] [SEED=RANDOM | n] [MCSAMPLES=30000]].

Each case is a subject measured once under each of the two or more variables; a case missing on any of them is left out. BF10 weighs different condition means against equal ones with the subjects as a random effect. BIC uses a closed-form approximation from the sums of squares of conditions, subjects and the total. ROUDER averages the factor of a mixed model over MCSAMPLES draws of the two scale parameters, from SEED; it uses the regression weights only. The posterior of each condition mean is the normal large-sample approximation, which needs no prior. PLOT draws the posterior densities of the listed means as chart data.

Example

BAYES REPEATED trial1 trial2 trial3 trial4
  /INFERENCE ANALYSIS=BOTH /ESTBF COMPUTATION=ROUDER /CRITERIA SEED=731.

statscraft help BAYES REPEATED prints the same text in the terminal. All commands

Statscraft 0.61.0, release v0.61.0

BAYES LOGLINEAR

Bayesian test of independence in a two-way table, with simulated interaction terms.

Syntax

BAYES LOGLINEAR /TABLE rowvar BY colvar
   [/INFERENCE ANALYSIS=POSTERIOR | BAYESFACTOR | BOTH]
   [/ESTBF [MODEL=MULTINOMIAL | POISSON | NONPARAMETRIC] [FIX_MARGIN=TOTAL | ROW | COLUMN]
           [PRIOR_TYPE=CONJUGATE | MIXTURE_DIRICHLET | INTRINSIC] [SHAPEPARAMS=values]
           [SCALEPARAM=DATA | b] [LAMBDAS=values]]
   [/PRINT [SUPPRESS_TABLE=FALSE | TRUE] [CELLS=OBSERVED ROW COLUMN EXPECTED TOTAL ALL]
           [STATISTICS=CHISQ LRT]]
   [/CRITERIA [CILEVEL=95] [SEED=RANDOM | n] [TOL=0.000001] [MAXITER=2000]
              [POSTSAMPLES=10000] [ORDER=ASCENDING | DESCENDING]].

The table counts cases valid on both variables with rounded case weights; only categories that occur count, and ORDER sorts both of them. Every Bayes factor is BF01, for independence. CONJUGATE puts gamma priors with the shapes of SHAPEPARAMS (1 for every cell; one value, or one row of values per table row with ‘;’ between rows) on the cells; FIX_MARGIN says whether the grand total, the row totals or the column totals are fixed by the design. POISSON fixes nothing and uses the gamma scale SCALEPARAM (DATA: rows times columns times the smallest shape over N). MIXTURE_DIRICHLET mixes symmetric Dirichlet priors over a log-Cauchy weight, by quadrature with TOL and MAXITER. INTRINSIC needs a 2 x 2 table (others fall back to the mixture with a warning). NONPARAMETRIC needs FIX_MARGIN=ROW with two rows or COLUMN with two columns; LAMBDAS holds one Dirichlet parameter, or one per free category.

The posterior part draws POSTSAMPLES cell probability sets from SEED and reports each log odds ratio against the last row and column, with a simultaneous credible region for all of them. PRINT shows the crosstab (observed counts by default) and, for CHISQ, Pearson’s chi-square, the continuity correction of a 2 x 2 table and Fisher’s test when an expected count is below 5; LRT adds the likelihood ratio. Keywords with an underscore may be written without it or as two words.

Example

BAYES LOGLINEAR /TABLE ferry_route BY ticket_class
  /INFERENCE ANALYSIS=BOTH /ESTBF MODEL=MULTINOMIAL FIX_MARGIN=ROW PRIOR_TYPE=CONJUGATE
  /PRINT CELLS=OBSERVED ROW STATISTICS=CHISQ LRT /CRITERIA SEED=4417.

statscraft help BAYES LOGLINEAR prints the same text in the terminal. All commands

Statscraft 0.61.0, release v0.61.0

POWER MEANS ONESAMPLE

Power or sample size of a one-sample t-test of a mean.

Syntax

POWER MEANS ONESAMPLE /PARAMETERS [TEST=NONDIRECTIONAL | DIRECTIONAL] [SIGNIFICANCE=0.05]
                      N=n | POWER=powers  SD=sd  MEAN=mean  [NULL=0]
                      [/PLOT [N[(low high)]] [ES[(low high)]] [N_XAXIS[(low high)] ES_YAXIS[(low high)]]
                             [N_YAXIS[(low high)] ES_XAXIS[(low high)]] [VROTATE(10)] [HROTATE(325)]].

powers: one or more values between 0 and 1, and at most one grid low TO high BY step.

Needs no data. With N (a whole number above 1) the table gives the power of the test of MEAN against NULL when the population standard deviation is SD; with POWER it gives, for each power, the smallest N that reaches it and the power that N actually has. The power comes from the noncentral t with N - 1 df and noncentrality (MEAN - NULL) / SD * sqrt(N); the effect size (MEAN - NULL) / SD shows unsigned for a two-sided test. A one-sided test looks in the direction of the effect. PLOT gives power curves as chart data: N over sample sizes (default from 2 to twice the table’s N), ES over effect sizes (default 0 to twice the effect, or from minus to plus that for a one-sided test; within -5 and 5), and a pair of _XAXIS and _YAXIS keywords a surface over both. With several powers only the N chart is drawn, over the sizes the table found. VROTATE and HROTATE are accepted; the chart data has no viewing angle.

Example

POWER MEANS ONESAMPLE /PARAMETERS SD=12 MEAN=104 NULL=100 POWER=0.8 0.9
  /PLOT N.

statscraft help POWER MEANS ONESAMPLE prints the same text in the terminal. All commands

Statscraft 0.61.0, release v0.61.0

POWER MEANS INDEPENDENT

Power or group sizes of a t-test comparing the means of two independent groups.

Syntax

POWER MEANS INDEPENDENT /PARAMETERS [TEST=NONDIRECTIONAL | DIRECTIONAL] [SIGNIFICANCE=0.05]
                        N=n1 n2 | POWER=powers [NRATIO=1]  SD=sd | sd1 sd2  MEAN=difference | mean1 mean2
                        [/PLOT [NRATIO[(low high)]] [ES[(low high)]] [NRATIO_XAXIS[(low high)] ES_YAXIS[(low high)]]
                               [NRATIO_YAXIS[(low high)] ES_XAXIS[(low high)]] [VROTATE(10)] [HROTATE(325)]].

Needs no data. One SD assumes equal variances: df n1 + n2 - 2 and effect size difference / SD. Two different SDs give the separate-variances test with Welch’s df, and the table shows the mean difference instead of an effect size. Two MEAN values are the group means, one is their difference. With POWER the table gives n1 (the smallest that reaches the power) and n2 = NRATIO * n1 rounded up (at least 2), with the power they actually have. NRATIO takes 0.01 to 100. PLOT: NRATIO over n2 / n1 with n1 + n2 kept (default 0.2 to 5), ES over the effect size, or the mean difference with two SDs (default 0 to twice the table’s value). The other rules are those of POWER MEANS ONESAMPLE.

Example

POWER MEANS INDEPENDENT /PARAMETERS SD=8 11 MEAN=31 25 POWER=0.85 NRATIO=2
  /PLOT ES(0 10).

statscraft help POWER MEANS INDEPENDENT prints the same text in the terminal. All commands

Statscraft 0.61.0, release v0.61.0

POWER MEANS RELATED

Power or number of pairs of a paired t-test.

Syntax

POWER MEANS RELATED /PARAMETERS [TEST=NONDIRECTIONAL | DIRECTIONAL] [SIGNIFICANCE=0.05]
                    NPAIRS=n | POWER=powers  SD=sd | sd1 sd2  [RHO=0.5]  MEAN=difference | mean1 mean2
                    [/PLOT [NPAIRS[(low high)]] [ES[(low high)]] [NPAIRS_XAXIS[(low high)] ES_YAXIS[(low high)]]
                           [NPAIRS_YAXIS[(low high)] ES_XAXIS[(low high)]] [VROTATE(10)] [HROTATE(325)]].

Needs no data. The test is the one-sample t-test of the differences within pairs. One SD is the standard deviation of those differences; two are those of the two measures, combined with their correlation RHO (-1 to 1, not 0) as sqrt(sd1^2 + sd2^2 - 2 RHO sd1 sd2). RHO is ignored with one SD. NPAIRS is a whole number above 1; the NPAIRS chart range lies within 2 and 5000. The other rules are those of POWER MEANS ONESAMPLE.

Example

POWER MEANS RELATED /PARAMETERS SD=6.5 7 RHO=0.7 MEAN=3 NPAIRS=40 TEST=DIRECTIONAL
  /PLOT NPAIRS(10 80).

statscraft help POWER MEANS RELATED prints the same text in the terminal. All commands

Statscraft 0.61.0, release v0.61.0

POWER PROPORTIONS ONESAMPLE

Power or sample size of a test of one proportion against a hypothesized value.

Syntax

POWER PROPORTIONS ONESAMPLE /PARAMETERS [TEST=NONDIRECTIONAL | DIRECTIONAL] [SIGNIFICANCE=0.05]
                            N=n | POWER=powers  [NULL=0.5]  ALTERNATIVE=p
                            [ESTIMATE=NORMAL | BINOMIAL] [CONTINUITY=FALSE | TRUE] [TIMER=minutes]
                            [/PLOT [N[(low high)]] [NULL] [ALTERNATIVE] [DIFF] [N_XAXIS[(low high)] DIFF_YAXIS]
                                   [N_YAXIS[(low high)] DIFF_XAXIS] [NULL_XAXIS ALTERNATIVE_YAXIS]
                                   [NULL_YAXIS ALTERNATIVE_XAXIS] [VROTATE(10)] [HROTATE(325)]].

Needs no data. NULL and ALTERNATIVE lie between 0 and 1, and differ when POWER is given.

NORMAL uses the normal approximation, with a continuity correction of 1 / (2 sqrt(n)) when CONTINUITY=TRUE. BINOMIAL counts the exact binomial rejection region at NULL and its probability at ALTERNATIVE, up to 500 trials; above that the normal approximation is used with a warning. Because exact power rises in steps, the sample size search checks smaller sizes and then counts upwards until the power is reached. TIMER stops that search after so many minutes, with no result. A one-sided test looks in the direction of ALTERNATIVE. PLOT charts power over N, over NULL or ALTERNATIVE (the other kept), over DIFF = ALTERNATIVE - NULL with NULL kept, and surfaces over N and DIFF or NULL and ALTERNATIVE; proportion axes run from 0.01 to 0.99.

Example

POWER PROPORTIONS ONESAMPLE /PARAMETERS NULL=0.3 ALTERNATIVE=0.42 POWER=0.8 0.9
  ESTIMATE=BINOMIAL.

statscraft help POWER PROPORTIONS ONESAMPLE prints the same text in the terminal. All commands

Statscraft 0.61.0, release v0.61.0

POWER PROPORTIONS INDEPENDENT

Power or group sizes of a test comparing two independent proportions.

Syntax

POWER PROPORTIONS INDEPENDENT /PARAMETERS [TEST=NONDIRECTIONAL | DIRECTIONAL] [SIGNIFICANCE=0.05]
                              N=n1 n2 | POWER=powers [NRATIO=1]  PROPORTIONS=p1 p2
                              [METHOD=CHISQ | T | LRT | FISHER] [ESTIMATE=NORMAL | BINOMIAL]
                              [CONTINUITY=FALSE | TRUE] [POOLED=TRUE | FALSE] [TIMER=minutes]
                              [/PLOT [NRATIO[(low high)]] [RISK_DIFF] [RISK_RATIO[(low high)]] [ODDS_RATIO[(low high)]]
                                     [N1_XAXIS[(low high)] N2_YAXIS[(low high)]] [N1_YAXIS[(low high)] N2_XAXIS[(low high)]]
                                     [P1_XAXIS P2_YAXIS] [P1_YAXIS P2_XAXIS] [VROTATE(10)] [HROTATE(325)]].

Needs no data. The table shows the risk difference p1 - p2, the risk ratio p1 / p2 and the odds ratio. METHOD picks the test: CHISQ the z (chi-square) test, with a pooled or separate standard error (POOLED) and optionally a continuity correction; T a t-test of the 0/1 values (pooled or not); LRT the likelihood ratio test; FISHER Fisher’s exact test, by the arcsine approximation (it needs at least 0.5 / p successes and failures in the right groups, else the power is missing). With ESTIMATE=BINOMIAL and at most 500 trials in all, the power sums the binomial probabilities of every pair of outcomes the test rejects (for FISHER, the exact conditional test); with POWER and FISHER the size search uses the chi-square test instead, with a warning. With POWER the table gives n1 and n2 = NRATIO * n1 rounded up (at least 1); the directional chi-square sizes come from a closed formula. A one-sided test looks in the direction of p1 - p2. PLOT: NRATIO with n1 + n2 kept (default 0.2 to 5), RISK_DIFF, RISK_RATIO and ODDS_RATIO by moving p1 with p2 kept, and surfaces over the two group sizes (default 1 to twice each size) or the two proportions.

Example

POWER PROPORTIONS INDEPENDENT /PARAMETERS PROPORTIONS=0.22 0.35 N=90 110
  METHOD=T POOLED=FALSE /PLOT RISK_RATIO.

statscraft help POWER PROPORTIONS INDEPENDENT prints the same text in the terminal. All commands

Statscraft 0.61.0, release v0.61.0

POWER PROPORTIONS RELATED

Power or number of pairs of McNemar’s test of two paired proportions.

Syntax

POWER PROPORTIONS RELATED /PARAMETERS [TEST=NONDIRECTIONAL | DIRECTIONAL] [SIGNIFICANCE=0.05]
                          NPAIRS=n | POWER=powers  VALUES=PROPORTIONS(a b) | COUNTS(a b)
                          [MARGINAL=FALSE | TRUE] [CORRELATION=0.5] [ESTIMATE=NORMAL | BINOMIAL] [TIMER=minutes]
                          [/PLOT [NPAIRS[(low high)]] [RISK_DIFF] [RISK_RATIO[(low high)]] [ODDS_RATIO[(low high)]]
                                 [CORRELATION] [DISCORDANT] [MARGINAL] [VROTATE(10)] [HROTATE(325)]].

Needs no data. A pair is a success or failure on a first and a second occasion. With MARGINAL=FALSE, a is the share of pairs with success first and failure second and b the reverse; with TRUE, a and b are the success rates of the first and second occasion, turned into those two shares through their CORRELATION (between -1 and 1). COUNTS give the numbers of such pairs and need NPAIRS. The risk difference is b - a in both readings, the risk and odds ratios compare the second discordant share with the first. NORMAL uses the normal approximation; BINOMIAL averages the exact conditional binomial test over the number of discordant pairs, up to 500 pairs. PLOT: NPAIRS (within 2 and 2500), RISK_DIFF, RISK_RATIO and ODDS_RATIO by moving b with a kept, CORRELATION (MARGINAL=TRUE only), and surfaces over the two discordant shares (DISCORDANT) or the two success rates (MARGINAL, with TRUE).

Example

POWER PROPORTIONS RELATED /PARAMETERS VALUES=PROPORTIONS(0.6 0.45) MARGINAL=TRUE
  CORRELATION=0.3 POWER=0.9 /PLOT CORRELATION.

statscraft help POWER PROPORTIONS RELATED prints the same text in the terminal. All commands

Statscraft 0.61.0, release v0.61.0

POWER ONEWAY ANOVA

Power or group sizes of a one-way analysis of variance, its contrasts and pairwise comparisons.

Syntax

POWER ONEWAY ANOVA /PARAMETERS [SIGNIFICANCE=0.05]  GROUP_SIZES=n1 n2 ... | POWER=powers
                   POOLED_SD=sd  GROUP_MEANS=m1 m2 ...  [GROUP_WEIGHTS=EQUAL | w1 w2 ...]
                   [/CONTRAST [COEFFICIENTS=c1 c2 ...] [TEST=NONDIRECTIONAL | DIRECTIONAL]
                              [PAIRWISE=FALSE | TRUE] [ADJUST=BONFERRONI | SIDAK | LSD]]
                   [/PLOT [TOTAL_N[(low high)]] [POOLED_SD[(low high)]]
                          [TOTAL_N_XAXIS[(low high)] POOLED_SD_YAXIS[(low high)]]
                          [TOTAL_N_YAXIS[(low high)] POOLED_SD_XAXIS[(low high)]] [VROTATE(10)] [HROTATE(325)]].

Needs no data. Each group has a size (a whole number of at least 2) and a mean; all share POOLED_SD. The overall F test of equal means gets its power from the noncentral F with J - 1 and N - J df, its effect size being the root mean square standardized effect. COEFFICIENTS add a test of one contrast (noncentral t, one- or two-sided by TEST); coefficients that do not add up to 0 are corrected in the last group (the one before it when only the last is not 0), with a warning. PAIRWISE=TRUE adds a two-sided test of every pair of groups at the significance level split by Bonferroni, Sidak or not at all (LSD). With POWER each test gets its own sizes: the total is searched with the groups in the proportions of GROUP_WEIGHTS (each 1 to 100, equal by default), then every group is rounded up (at least 2); a Group Sizes table lists them.

PLOT charts the overall test: TOTAL_N over the total size with the groups kept in proportion (default from the smallest total that keeps every group at 2 or more to twice the table’s total), POOLED_SD over the standard deviation (default half to twice the value given), and the pair of _XAXIS and _YAXIS keywords a surface over both.

Example

POWER ONEWAY ANOVA /PARAMETERS GROUP_MEANS=48 52 57 POOLED_SD=9 POWER=0.85
  GROUP_WEIGHTS=2 1 1 /CONTRAST COEFFICIENTS=-2 1 1 PAIRWISE=TRUE ADJUST=SIDAK.

statscraft help POWER ONEWAY ANOVA prints the same text in the terminal. All commands

Statscraft 0.61.0, release v0.61.0

POWER PEARSON ONESAMPLE

Power or sample size of a test of one Pearson correlation against a hypothesized value.

Syntax

POWER PEARSON ONESAMPLE /PARAMETERS [TEST=NONDIRECTIONAL | DIRECTIONAL] [SIGNIFICANCE=0.05]
                        N=n | POWER=powers  [NULL=0]  ALTERNATIVE=r  [ADJUST_BIAS=TRUE | FALSE]
                        [/PLOT [N[(low high)]] [NULL] [ALTERNATIVE] [DIFF] [N_XAXIS[(low high)] DIFF_YAXIS]
                               [N_YAXIS[(low high)] DIFF_XAXIS] [NULL_XAXIS ALTERNATIVE_YAXIS]
                               [NULL_YAXIS ALTERNATIVE_XAXIS] [VROTATE(10)] [HROTATE(325)]].

Needs no data. The test compares Fisher’s z of the sample correlation with that of NULL; its standard error is 1 / sqrt(N - 3) and the power comes from the normal approximation. N is a whole number above 3. NULL and ALTERNATIVE lie from -1 to 1; with POWER they lie strictly inside and differ. ADJUST_BIAS=TRUE (the default) adds the small-sample corrections to the mean and spread of z; FALSE leaves them out. A one-sided test looks in the direction of ALTERNATIVE - NULL. PLOT charts power over N, NULL, ALTERNATIVE or DIFF = ALTERNATIVE - NULL (NULL kept), and surfaces over N and DIFF or NULL and ALTERNATIVE; correlation axes run from -0.99 to 0.99.

Example

POWER PEARSON ONESAMPLE /PARAMETERS NULL=0.15 ALTERNATIVE=0.4 POWER=0.8 0.9
  /PLOT N.

statscraft help POWER PEARSON ONESAMPLE prints the same text in the terminal. All commands

Statscraft 0.61.0, release v0.61.0

POWER SPEARMAN ONESAMPLE

Power or sample size of a test of one Spearman rank correlation against a hypothesized value.

Syntax

POWER SPEARMAN ONESAMPLE /PARAMETERS [TEST=NONDIRECTIONAL | DIRECTIONAL] [SIGNIFICANCE=0.05]
                         N=n | POWER=powers  [NULL=0]  ALTERNATIVE=r  [VARIANCE=BW | FHP | CC]
                         [/PLOT [N[(low high)]] [NULL] [ALTERNATIVE] [DIFF] [N_XAXIS[(low high)] DIFF_YAXIS]
                                [N_YAXIS[(low high)] DIFF_XAXIS] [NULL_XAXIS ALTERNATIVE_YAXIS]
                                [NULL_YAXIS ALTERNATIVE_XAXIS] [VROTATE(10)] [HROTATE(325)]].

Needs no data. As POWER PEARSON ONESAMPLE, with Fisher’s z of the rank correlation, whose variance VARIANCE chooses: BW (Bonett and Wright, the default) (1 + ALTERNATIVE^2 / 2) / (N - 3); FHP (Fieller, Hartley and Pearson) 1.06 / (N - 3); CC (Caruso and Cliff) 1 / (N - 2) + |z of ALTERNATIVE| / (6 N + 4 sqrt(N)). N is above 3, above 2 with CC. There is no bias adjustment.

Example

POWER SPEARMAN ONESAMPLE /PARAMETERS ALTERNATIVE=-0.35 N=45 VARIANCE=CC
  TEST=DIRECTIONAL /PLOT DIFF.

statscraft help POWER SPEARMAN ONESAMPLE prints the same text in the terminal. All commands

Statscraft 0.61.0, release v0.61.0

POWER PARTIALCORR

Power or sample size of a test of one partial correlation against a hypothesized value.

Syntax

POWER PARTIALCORR /PARAMETERS [TEST=NONDIRECTIONAL | DIRECTIONAL] [SIGNIFICANCE=0.05]
                  PARTIALOUT=k  N=n | POWER=powers  [NULL=0]  ALTERNATIVE=r
                  [/PLOT [N[(low high)]] [PARTIALOUT] [NULL] [ALTERNATIVE] [DIFF]
                         [N_XAXIS[(low high)] DIFF_YAXIS] [N_YAXIS[(low high)] DIFF_XAXIS]
                         [NULL_XAXIS ALTERNATIVE_YAXIS] [NULL_YAXIS ALTERNATIVE_XAXIS] [VROTATE(10)] [HROTATE(325)]].

Needs no data. As POWER PEARSON ONESAMPLE with the bias adjustment, for the correlation of two variables with PARTIALOUT others (a whole number, 0 or more) held fixed: each of them costs one degree of freedom, so the standard error of z is 1 / sqrt(N - 3 - k) and N must exceed k + 3.

PLOT adds PARTIALOUT, power over the number held fixed (from 0 to N - 4).

Example

POWER PARTIALCORR /PARAMETERS PARTIALOUT=4 ALTERNATIVE=0.3 NULL=0.05 N=120
  /PLOT PARTIALOUT N_XAXIS DIFF_YAXIS.

statscraft help POWER PARTIALCORR prints the same text in the terminal. All commands

Statscraft 0.61.0, release v0.61.0

POWER UNIVARIATE LINEAR

Power or sample size of the F test of a set of predictors in a linear regression.

Syntax

POWER UNIVARIATE LINEAR /PARAMETERS [SIGNIFICANCE=0.05] [MODEL=FIXED | RANDOM]  N=n | POWER=powers
                        TOTAL_PREDICTORS=p  TEST_PREDICTORS=q
                        PARTIAL_CORR=r | FULL_MODEL=r2 NESTED_MODEL=r2  [INTERCEPT=TRUE | FALSE]
                        [/PLOT [N[(low high)]] [PARTIAL_CORR] [N_XAXIS[(low high)] PARTIAL_CORR_YAXIS]
                               [N_YAXIS[(low high)] PARTIAL_CORR_XAXIS] [VROTATE(10)] [HROTATE(325)]].

Needs no data. A regression with p predictors (besides the intercept) tests whether q of them add nothing to the other p - q. The effect is the multiple partial correlation of the outcome with the q, or comes from the squared multiple correlations of the full and the nested model as (full - nested) / (1 - nested). The F test has q and N - p - 1 df (N - p without the intercept). MODEL=FIXED takes the predictor values as fixed: noncentral F with noncentrality N r^2 / (1 - r^2). RANDOM takes outcome and predictors as jointly normal and uses the exact distribution of the sample squared multiple partial correlation. q is from 1 to p (below p with FULL_MODEL); PARTIAL_CORR lies strictly between -1 and 1 and is not 0 with POWER; the squared correlations lie strictly between 0 and 1, full not below nested (above it with POWER). N is at least p + 2 (p + 1 without the intercept). PLOT charts power over N and over the partial correlation (default 0 to 0.99), and a surface over both.

Example

POWER UNIVARIATE LINEAR /PARAMETERS TOTAL_PREDICTORS=7 TEST_PREDICTORS=3 FULL_MODEL=0.31
  NESTED_MODEL=0.24 MODEL=RANDOM POWER=0.8 /PLOT N.

statscraft help POWER UNIVARIATE LINEAR prints the same text in the terminal. All commands

Statscraft 0.61.0, release v0.61.0

SIMPLAN

A simulation plan: distributions of the inputs, fitted to the data or given, their correlations and the targets of a model.

Syntax

SIMPLAN CREATE [SOURCE=AUTOFIT]
  [/MODEL FILE='file' [CUSTOM=NO | YES]]
  [/TARGETOPTS TARGET=field[(FORMAT=type[,d])] ... [COMMENT='text'] [OUTPUT=YES | NO]
              [TARGETFILTER=NO | YES([MIN=LO | value[(INCLUSIVE | EXCLUSIVE)]] [MAX=HI | value[(...)]])]] ...
  /SIMINPUT INPUT=field[(MAPTO=name FORMAT=type[,d])] ... [OUTPUT=YES | NO]
            [TYPE=AUTOFIT[(DEFAULT | distributions)] | MANUAL] [DISTRIBUTION=name(PARAM=values ...)]
            [MINVAL=n] [MAXVAL=n] ...
  [/FIXEDINPUT INPUT=field ... VALUE=n | ITERATIONS=VALUES(n ...) | RANGE(MIN=n MAX=n N=k)] ...
  [/CORRELATIONS VARORDER=fields CORRMATRIX=1; r, 1; r, r, 1 ...]
  [/AUTOFIT [NCASES=ALL | n] [FIT=AD | KS] [MAXITERATIONS=100] [BINS=100]]
  [/STOPCRITERIA [MAXCASES=100000] [TARGET=field
                TYPE=MEAN(THRESH=n UNIT=PERCENT | VALUE [CILEVEL=95]) |
                     TAIL(UNIT=PERCENTILE | VALUE THRESH=n [SIDE=RIGHT | LEFT] FREQUENCY=n)]]
  [/MISSING CLASSMISSING=EXCLUDE | INCLUDE] [/VALUELABELS VARIABLES=fields VALUES=value 'label' ...] ...
  /PLAN FILE='file' [DISPLAY=YES | NO].
SIMPLAN VIEW /PLAN FILE='file'.

Distributions and their parameters: BERNOULLI(PROB) BETA(SHAPE1 SHAPE2) BINOM(N PROB) CATEGORICAL(CATS=values PROBS=values) EMPIRICAL EXP(SCALE) GAMMA(SHAPE SCALE) LNORMAL(A B) NEGBIN([TYPE=FAILURES | TRIALS] THRESHOLD PROB) NORMAL(MEAN STDDEV) POISSON(MEAN) TRIANGULAR(MIN MAX MODE) UNIFORM(MIN MAX) USER_RANGES(MIN=values MAX=values PROBS=values) WEIBULL(A B [C]). The SCALE of EXP and GAMMA is the rate, as in the RV and CDF functions; LNORMAL A is the median and B the standard deviation of the logarithm; WEIBULL A is the scale, B the shape and C the origin. The model is a file that BEGIN EXPR wrote, or a plan whose model is taken. Every input of a model is simulated (SIMINPUT) or fixed (FIXEDINPUT); without MODEL the plan only generates the SIMINPUT fields. AUTOFIT (default) fits each input to its field in the active dataset (MAPTO names another field) by maximum likelihood: a nominal field gets the categorical distribution, an ordinal one the binomial, negative binomial (failures) and Poisson by the chi-square statistic, a scale one the beta, exponential, gamma, lognormal, normal, triangular, uniform and two-parameter Weibull by the Anderson-Darling statistic (or Kolmogorov-Smirnov with FIT=KS); the smallest statistic wins and a Goodness of Fit table shows them all with their p-values where known. Weights count; cases missing on any fitted input are left out (user-missing values of a categorical fit count with CLASSMISSING=INCLUDE). Without CORRELATIONS the Pearson correlations of the fields in the data are used. MINVAL and MAXVAL cut the distribution. Several values of one parameter, several PROBS sets or FIXEDINPUT ITERATIONS run one simulation per value (sensitivity analysis). The plan is Statscraft’s own JSON. SPLIT FILE is not used.

Example

SIMPLAN CREATE /MODEL FILE='margin.json' CUSTOM=YES
  /SIMINPUT INPUT=units TYPE=MANUAL DISTRIBUTION=TRIANGULAR(MIN=800 MAX=1400 MODE=1000)
  /SIMINPUT INPUT=unit_cost /FIXEDINPUT INPUT=unit_price VALUE=12
  /PLAN FILE='margin.splan'.

statscraft help SIMPLAN prints the same text in the terminal. All commands

Statscraft 0.61.0, release v0.61.0

SIMRUN

Runs a simulation plan: draws the inputs, computes the targets and describes their distributions.

Syntax

SIMRUN /PLAN FILE='file' [/CRITERIA [REPRESULTS=TRUE | FALSE] [SEED=629111597]]
  [/DISTRIBUTION [DISPLAY=[PDF] [CDF] [NONE]] [CDFORDER=[ASCENDING] [DESCENDING]] [SCALE=...] [CATEGORICAL=...]]
  [/SCATTERPLOT [DISPLAY=NO | YES] [ROWSIZE=n]] [/BOXPLOT [DISPLAY=NO | YES] [OVERLAYTARGETS=...]]
  [/TORNADO [DISPLAY=YES | NO] [TYPE=[CORR] [DELTASTDDEV(k)] [VARIANCE]]]
  [/PRINT [DESCRIPTIVES=YES[(CILEVEL=95)] | NO] [PERCENTILES=NO | YES([NTILES=k] [PTILES=values])]
          [ASSOCIATIONS=NO | YES]]
  [/OPTIONS VIZSTYLESHEET='name'] [/OUTFILE FILE='file' | dataset | *].

Each case draws standard normal numbers from a Mersenne Twister started by SEED, correlates them (the correlation of each pair of normals is searched so that the inputs, after the inverse distribution function, reach the planned correlation) and turns them into the inputs; the model’s expressions then give the targets. Cases are drawn up to MAXCASES, or until the stopping rule of the plan holds, for each value of a sensitivity analysis. Tables: Target Statistics (mean, standard deviation, median, minimum, maximum, the confidence interval of the mean, 5th and 95th percentiles), Target Categories for an ordinal or nominal target, Input Statistics, Target Percentiles, Correlations of Inputs (ASSOCIATIONS), and the tornado tables: the correlation with each input, the mean change of the target when an input moves DELTASTDDEV standard deviations down and up, and each input’s total share of the target’s variance (Sobol, from a second sample). Charts: the histogram (PDF) and the cumulative distribution (CDF) of each target, the boxplot, scatterplots of each target with each input (the first 5000 cases) and tornado bar charts. SCALE, CATEGORICAL, ROWSIZE, OVERLAYTARGETS and OPTIONS are accepted and change nothing. OUTFILE writes every case: the targets, the inputs and, with a sensitivity analysis, Iteration. Without a model only the input statistics, ASSOCIATIONS and OUTFILE apply.

Example

SIMRUN /PLAN FILE='margin.splan' /CRITERIA SEED=4711
  /TORNADO TYPE=CORR VARIANCE /PRINT PERCENTILES=YES(NTILES=4) /OUTFILE FILE='draws.sav'.

statscraft help SIMRUN prints the same text in the terminal. All commands

Statscraft 0.61.0, release v0.61.0

BEGIN EXPR

Starts a block of expressions that END EXPR saves as a model for SIMPLAN.

Syntax

BEGIN EXPR /OUTFILE PREPXML='file'.

NUMERIC and STRING, VARIABLE LEVEL, VALUE LABELS and COMPUTE commands, then END EXPR.

Nothing in the block touches the active dataset. Each COMPUTE gives a target, in order, and may use the targets before it; a variable is computed once. NUMERIC names the inputs the active dataset lacks, and only those. Targets and declared inputs are scale unless VARIABLE LEVEL says otherwise. The file is Statscraft’s own JSON (not XML); a name starting with *\ is kept in memory for the session.

Example

BEGIN EXPR /OUTFILE PREPXML='margin.json'.
NUMERIC units unit_price.
COMPUTE margin = units * (unit_price - unit_cost).
END EXPR.

statscraft help BEGIN EXPR prints the same text in the terminal. All commands

Statscraft 0.61.0, release v0.61.0

END EXPR

Ends the BEGIN EXPR block and writes its model file.

Syntax

END EXPR.

Example

END EXPR.

statscraft help END EXPR prints the same text in the terminal. All commands

Statscraft 0.61.0, release v0.61.0

FACTOR

Factor analysis: principal components and six factoring methods, rotations, factor scores.

Syntax

FACTOR VARIABLES=varlist | MATRIX=IN(COR=* | 'file' | COV=* | 'file' | FAC=* | 'file')
       [/MISSING=[LISTWISE | PAIRWISE | MEANSUB] [INCLUDE]] [/SELECT=var(value)]
       [/ANALYSIS=varlist] [/METHOD=CORRELATION | COVARIANCE] [/MATRIX=OUT(COR | COV | FAC | FSC = file | *)]
       [/PRINT=[DEFAULT] [INITIAL] [EXTRACTION] [ROTATION] [UNIVARIATE] [CORRELATION] [COVARIANCE]
               [SIG] [DET] [INV] [REPR] [AIC] [KMO] [FSCORE] [ALL]]
       [/FORMAT=[SORT] [BLANK(n)] [DEFAULT]] [/DIAGONAL=values | DEFAULT]
       [/PLOT=[EIGEN] [ROTATION[(f1,f2) ...]]]
       [/CRITERIA=[FACTORS(n)] [MINEIGEN(1)] [ITERATE(25)] [ECONVERGE(.001)] [RCONVERGE(.0001)]
                  [KAISER | NOKAISER] [DELTA(0)] [KAPPA(4)] [DEFAULT]]
       [/EXTRACTION=PC | PAF | ALPHA | IMAGE | ULS | GLS | ML]
       [/ROTATION=VARIMAX | EQUAMAX | QUARTIMAX | OBLIMIN[(delta)] | PROMAX[(kappa)] | NOROTATE]
       [/SAVE=[REG | BART | AR] [(n | ALL [rootname])]].

The analysis is of the correlation matrix of the ANALYSIS variables (default all of VARIABLES).

LISTWISE (default) uses the cases valid on every variable of VARIABLES; PAIRWISE each pair’s own cases; MEANSUB puts the mean in place of a missing value. SELECT computes the matrix from the cases with that value (a missing value never matches, a user-missing one does with INCLUDE; SELECT cannot go with MATRIX=IN), while scores are saved for all cases. CRITERIA applies to the EXTRACTION and ROTATION that follow it. The number of factors is FACTORS(n), else the count of eigenvalues above MINEIGEN; FACTORS wins within one CRITERIA, and a MINEIGEN on a later CRITERIA replaces an earlier FACTORS. Without EXTRACTION the extraction is PC with VARIMAX; with EXTRACTION but no ROTATION the factors are not rotated. A later ANALYSIS cancels the PRINT, DIAGONAL, EXTRACTION, ROTATION and SAVE before it, with a warning. Tables: Descriptive Statistics (UNIVARIATE), Correlation Matrix (CORRELATION, SIG, DET), Inverse of Correlation Matrix (INV), Covariance Matrix, KMO and Bartlett’s Test (KMO), Anti-image Matrices (AIC), Communalities, Total Variance Explained, Component or Factor Matrix, Goodness-of-fit Test (ML, GLS), Reproduced Correlations (REPR; Reproduced Covariances with METHOD=COVARIANCE), the rotated matrix with its transformation matrix, or Pattern, Structure and factor correlation matrices for OBLIMIN and PROMAX, Score Coefficient and Score Covariance Matrix (FSCORE). SORT orders the variables by the factor of their largest loading; BLANK(n) leaves out loadings below n in absolute value. SAVE adds scores by regression, Bartlett or Anderson-Rubin, named FAC1_1, FAC2_1 and so on, or rootname1, rootname2. MATRIX=IN reads a matrix file (ROWTYPE_ N, MEAN, STDDEV, CORR or COV, VARNAME_) from the active dataset or a file. Weighted when a weight variable is set. PLOT gives chart data: EIGEN the scree plot, every eigenvalue of the matrix analyzed against its number; ROTATION the loading plot, each variable at its loadings (rotated when there is a rotation) on the first two factors, with the third as depth when there are three or more, or one plot per pair given. METHOD=COVARIANCE analyzes the covariance matrix (with PC, PAF or IMAGE only; it needs the standard deviations in a correlation matrix file): the tables show the raw loadings and communalities beside the rescaled ones, the initial eigenvalues are those of the covariance matrix, MINEIGEN(n) counts in mean variances (mean image variances for IMAGE), and the rotation turns the raw loadings.

MATRIX=OUT(COR=file) or OUT(COV=file) writes the means, standard deviations, counts and the matrix (a file, a dataset or * for the active dataset), OUT(FAC=file) the loadings and OUT(FSC=file) the means, deviations and score coefficients. MATRIX=IN(FAC=file) reads a factor-loading matrix and gives its communalities, variance and loadings and the rotation asked for.

Example

FACTOR VARIABLES=q1 TO q10 /PRINT=INITIAL EXTRACTION ROTATION KMO /FORMAT=SORT BLANK(.3) /CRITERIA=MINEIGEN(1) /EXTRACTION=PC /ROTATION=VARIMAX /SAVE=REG(ALL).

statscraft help FACTOR prints the same text in the terminal. All commands

Statscraft 0.61.0, release v0.61.0

QUICK CLUSTER

K-means clustering of cases into a given number of clusters.

Syntax

QUICK CLUSTER varlist | ALL [/MISSING=[LISTWISE | PAIRWISE | DEFAULT] [INCLUDE]]
              [/FILE='file' | dataset] [/INITIAL=(values)]
              [/CRITERIA=[CLUSTER(2)] [NOINITIAL] [MXITER(10)] [CONVERGE(0)]]
              [/METHOD=KMEANS[(NOUPDATE | UPDATE)] | CLASSIFY]
              [/PRINT=[INITIAL] [CLUSTER] [ID(var)] [DISTANCE] [ANOVA] [NONE]]
              [/OUTFILE='file' | dataset] [/SAVE=[CLUSTER[(name)]] [DISTANCE[(name)]]].

Distances are Euclidean. Initial centers: by default the first k complete cases, then a case replaces a center when it lies farther from the centers than the two closest centers lie from each other (NOINITIAL keeps the first k cases); INITIAL gives them cluster by cluster, FILE reads them from the clustering variables of a data file. KMEANS moves each center to the mean of its cases after each pass (UPDATE after each case) until no center moves more than CONVERGE times the smallest distance between the initial centers, or MXITER passes; CLASSIFY keeps the initial centers. Then every case goes to its nearest center, and the final centers are the means of their cases. Tables: Initial Cluster Centers, Iteration History, Cluster Membership (CLUSTER, with ID), Final Cluster Centers, Distances between Final Cluster Centers (DISTANCE), ANOVA and Number of Cases in each Cluster. LISTWISE (default) leaves out a case missing on any variable; PAIRWISE uses the variables a case has. SAVE adds the cluster number and the distance to the classification center, named QCL_1, QCL_2 and so on unless given. OUTFILE writes the final centers with CLUSTER_. Weighted when a weight variable is set.

Example

QUICK CLUSTER q1 TO q5 /CRITERIA=CLUSTER(3) MXITER(20) /PRINT=INITIAL ANOVA /SAVE=CLUSTER(segment) DISTANCE.

statscraft help QUICK CLUSTER prints the same text in the terminal. All commands

Statscraft 0.61.0, release v0.61.0

CLUSTER

Hierarchical clustering of cases by one of 37 proximity measures and seven methods.

Syntax

CLUSTER varlist | /MATRIX=IN('file' | dataset | *) [/MATRIX=OUT('file' | dataset | *)]
        [/MEASURE=SEUCLID | EUCLID | COSINE | CORRELATION | BLOCK | CHEBYCHEV | MINKOWSKI(p) |
                  POWER(p,r) | CHISQ | PH2 | binary[(p[,np])]]
        [/METHOD=BAVERAGE | WAVERAGE | SINGLE | COMPLETE | CENTROID | MEDIAN | WARD [(rootname)] ...]
        [/PRINT=[SCHEDULE] [CLUSTER(min[,max])] [DISTANCE] [NONE]] [/SAVE=CLUSTER(min[,max])]
        [/ID=var] [/MISSING=EXCLUDE | INCLUDE] [/PLOT=[VICICLE | HICICLE[(min,max,inc)]] [DENDROGRAM] [NONE]].

binary: RR SM JACCARD DICE SS1 RT SS2 K1 SS3 K2 SS4 HAMANN OCHIAI SS5 PHI LAMBDA D Y Q BEUCLID SIZE PATTERN BSEUCLID BSHAPE DISPER VARIANCE BLWMN, from the 2 x 2 table of presence (p, default 1) and absence (np, default 0; with p alone every other value is absence). The items are the cases valid on every variable; the weight variable is not used. Each step joins the most similar pair of clusters (smallest distance or largest similarity) into the lower-numbered one and updates the proximities by the formula of the method; BAVERAGE (default) and WAVERAGE choose by the mean proximity between or within the clusters. Tables: Case Processing Summary, Proximity Matrix (DISTANCE), and for each method the Agglomeration Schedule (default; for WARD the coefficient is the within-cluster sum of squares) and Cluster Membership (CLUSTER), the clusters of a solution numbered in the order of their first case. ID labels the cases. SAVE adds the membership of each solution, named rootname plus the number of clusters, or CLUn_m. MATRIX=IN reads the rows of type PROX of a matrix file, a dissimilarity matrix unless the value label of PROX says SIMILARITY. SAVE with MATRIX=IN needs the matrix of the active dataset’s cases (one item per case, in its order), read from a file or a dataset, not *. Plots come as chart data for each method; a vertical icicle plot unless PLOT names others. The icicle plot shows the cluster of every case at each number of clusters, from min to max by inc (default 1 to the number of cases minus 1). The dendrogram holds every join with its coefficient, rescaled from 1 at the first join to 25 at the last. MATRIX=OUT writes the proximity matrix of the run (rows of type PROX, the same file PROXIMITIES writes: the ID variable or none, CASENO_, VARNAME_ and one VARn column per case) to a file, a dataset or the active dataset.

Example

CLUSTER q1 TO q5 /MEASURE=SEUCLID /METHOD=WARD /PRINT=SCHEDULE CLUSTER(2,4) /SAVE=CLUSTER(3).

statscraft help CLUSTER prints the same text in the terminal. All commands

Statscraft 0.61.0, release v0.61.0

TWOSTEP CLUSTER

Clusters of cases from continuous and categorical variables, the number of clusters chosen by BIC or AIC.

Syntax

TWOSTEP CLUSTER [/CONTINUOUS VARIABLES=varlist] [/CATEGORICAL VARIABLES=varlist]
                [/DISTANCE=LIKELIHOOD | EUCLIDEAN] [/NUMCLUSTERS=AUTO [15] [BIC | AIC] | FIXED=n]
                [/CRITERIA=[INITHRESHOLD(0)] [MXBRANCH(8)] [MXLEVEL(3)]] [/HANDLENOISE=0]
                [/INFILE FILE='file'] [/NOSTANDARDIZE [VARIABLES=varlist]] [/MISSING=EXCLUDE | INCLUDE] [/MEMALLOCATE=64]
                [/PRINT=[IC] [COUNT] [SUMMARY]] [/VIEWMODEL [DISPLAY=YES | NO] [EVALUATIONFIELDS=varlist]]
                [/SAVE CLUSTER [VARIABLE=name]] [/OUTFILE [MODEL='file'] [STATE='file']].

Step one reads the cases in file order into a tree of small subclusters: a case joins the nearest subcluster when it lies within the threshold, else it starts its own; a node holds at most MXBRANCH entries and the tree at most MXLEVEL levels below its root. A full tree is rebuilt with a larger threshold; with HANDLENOISE p it first puts aside the subclusters smaller than p percent of the largest, takes back those that later fit and calls the rest noise. Step two joins the subclusters, nearest pair first. LIKELIHOOD (default) measures how much the log-likelihood drops when two groups join, with normal continuous and multinomial categorical variables; EUCLIDEAN, the distance between group means, takes continuous variables only. AUTO compares 1 to 15 clusters (or the maximum given): BIC (default) or AIC gives a first count, at the first step whose change is less than 0.04 of the change from 1 to 2 clusters, and the ratios of the join distances settle it. Then every case goes to its nearest cluster; when the tree filled under HANDLENOISE, a case too far from every cluster goes to cluster -1. Continuous variables are standardized unless NOSTANDARDIZE names them; a constant one is left out.

Tables: Model Summary (unless DISPLAY=NO), Auto-Clustering (IC), Cluster Distribution (COUNT), Centroids and one frequency table per categorical variable (SUMMARY). Cases missing on any variable are left out; the weight variable is not used. SAVE adds the cluster numbers, named TSC_1, TSC_2 and so on unless given. OUTFILE writes Statscraft’s own JSON: MODEL the variables, their standardization and the final clusters, STATE the subclusters and settings of the tree (not with SPLIT FILE). INFILE updates a model whose STATE file an earlier run wrote: the saved subclusters go into the tree first and the cases of the active file follow, with the saved distance, threshold, branch and level limits, standardization and categories (the variables are named in the order of the file, a new category is an error, CRITERIA, DISTANCE, HANDLENOISE and MEMALLOCATE are ignored); the file itself is left as it is, the tables describe the cases of the active file and OUTFILE can write the updated model. The result depends on the order of the cases. DMCLUSTER is another name for the command.

Example

TWOSTEP CLUSTER /CONTINUOUS VARIABLES=spend visits /CATEGORICAL VARIABLES=region plan
  /NUMCLUSTERS=AUTO 8 BIC /PRINT=COUNT SUMMARY IC /SAVE CLUSTER VARIABLE=segment.

statscraft help TWOSTEP CLUSTER prints the same text in the terminal. All commands

Statscraft 0.61.0, release v0.61.0

DMCLUSTER

Another name for TWOSTEP CLUSTER.

Syntax

DMCLUSTER takes the subcommands of TWOSTEP CLUSTER and runs it.

Example

DMCLUSTER /CONTINUOUS VARIABLES=spend visits /PRINT=COUNT.

statscraft help DMCLUSTER prints the same text in the terminal. All commands

Statscraft 0.61.0, release v0.61.0

DETECTANOMALY

Unusual cases: peer groups by two-step clustering, an anomaly index and the variables behind it.

Syntax

DETECTANOMALY [/VARIABLES [CATEGORICAL=varlist] [SCALE=varlist] [ID=var] [EXCEPT=varlist]]
              [/HANDLEMISSING [APPLY=NO | YES] [CREATEMISPROPVAR=NO | YES]]
              [/CRITERIA [MINNUMPEERS=1] [MAXNUMPEERS=15] [MLWEIGHT=6] [NUMREASONS=1]
                         [PCTANOMALOUSCASES=5] [NUMANOMALOUSCASES=n] [ANOMALYCUTPOINT=2 | NONE]]
              [/SAVE [ANOMALY[(name)]] [PEERID[(name)]] [PEERSIZE[(name)]] [PEERPCTSIZE[(name)]]
                     [REASONVAR[(root)]] [REASONMEASURE[(root)]] [REASONVALUE[(root)]] [REASONNORM[(root)]]]
              [/PRINT [CPS] [ANOMALYLIST] [NORMS] [ANOMALYSUMMARY] [REASONSUMMARY] [NONE]] [/OUTFILE MODEL='file'].

Without CATEGORICAL and SCALE every variable but ID and EXCEPT is used, strings and nominal or ordinal variables as categorical. Keywords are written in full, each subcommand once. The cases are grouped into peer groups by two-step clustering (log-likelihood distance, the variances eased by the variable’s overall variance over MLWEIGHT, BIC choosing between MINNUMPEERS and MAXNUMPEERS). For each case, each variable’s share of the distance between the case and its peer group measures how far it strays; their sum over the peer group’s mean sum is the anomaly index, and a variable’s share of the sum its impact. The anomaly list takes the cases of highest index, PCTANOMALOUSCASES percent (rounded down) or NUMANOMALOUSCASES of them, keeping those with an index of at least ANOMALYCUTPOINT; its reasons are each case’s NUMREASONS variables of largest impact, with the value and the peer group’s norm (mean or mode).

Missing values leave the case out unless APPLY=YES, which puts the mean in for a continuous variable and makes missing a category of a categorical one; CREATEMISPROPVAR=YES then adds the share of missing values as a variable. A variable that does not vary is left out. Tables: Case Processing Summary (CPS), the anomaly index, peer and reason lists (ANOMALYLIST, the default), Scale and Categorical Variable Norms (NORMS), Anomaly Index Summary, Reason Summary.

SAVE adds AnomalyIndex, PeerId, PeerSize, PeerPctSize and per reason k ReasonVar_k, ReasonMeasure_k, ReasonValue_k and ReasonNorm_k, a free suffix added to a default name in use.

WEIGHT and SPLIT FILE are not used. OUTFILE MODEL writes Statscraft’s own JSON: the variables with their means and categories, and the peer groups.

Example

DETECTANOMALY /VARIABLES SCALE=amount days CATEGORICAL=channel ID=order_no
  /CRITERIA NUMREASONS=2 PCTANOMALOUSCASES=2 /SAVE ANOMALY PEERID REASONVAR /PRINT CPS ANOMALYLIST NORMS.

statscraft help DETECTANOMALY prints the same text in the terminal. All commands

Statscraft 0.61.0, release v0.61.0

OPTIMAL BINNING

Bins of scale variables: cuts chosen by MDLP against a guide variable, or by equal frequency.

Syntax

OPTIMAL BINNING /VARIABLES [GUIDE=var] BIN=varlist [SAVE=NO | YES [(INTO=new varlist)]]
                [/CRITERIA [PREPROCESS=EQUALFREQ[(BINS=1000)] | NONE] [METHOD=MDLP | EQUALFREQ[(BINS=10)]]
                           [LOWEREND=UNBOUNDED | OBSERVED] [UPPEREND=UNBOUNDED | OBSERVED]
                           [LOWERLIMIT=INCLUSIVE | EXCLUSIVE] [FORCEMERGE=0]]
                [/MISSING SCOPE=PAIRWISE | LISTWISE] [/OUTFILE RULES='file']
                [/PRINT [ENDPOINTS] [DESCRIPTIVES] [ENTROPY] [NONE]].

Every word is written in full and each subcommand given once. MDLP, the default when GUIDE names a numeric or string variable (at most 256 values), splits a range of values in two at the point that best separates the guide’s values, keeps the split when its information gain beats the minimum description length cost, and goes on in both halves. PREPROCESS first groups a variable with more distinct values than BINS into that many equal frequency groups, and MDLP splits only between groups. EQUALFREQ, the default without GUIDE, cuts at the 1/n, 2/n and further percentiles (empirical distribution with averaging); a variable with at most n distinct values gets a bin for each. FORCEMERGE r joins an inner bin smaller than r times its smaller neighbour to the neighbour that leaves the lower class entropy, in one pass. End points are data values: with LOWERLIMIT=INCLUSIVE a bin runs from its lower end point up to but not including its upper one, with EXCLUSIVE from above its lower one up to and including its upper one; the outer ends are unbounded, or the observed minimum and maximum with OBSERVED.

PAIRWISE uses each variable’s valid cases (with a valid guide for MDLP), LISTWISE the cases valid on all of them; user-missing values are missing. Weights are rounded to whole numbers.

Tables: End Points with the cases of each bin (ENDPOINTS, the default), Descriptive Statistics and Guide Variable Distribution (DESCRIPTIVES), Model Entropy (ENTROPY, MDLP only). SAVE adds the bin numbers of every case with a valid value as guide_var_bin (var_bin without a guide) or the INTO names. RULES writes syntax with the same bins for other data. SPLIT FILE is not used.

Example

OPTIMAL BINNING /VARIABLES GUIDE=churned BIN=tenure spend SAVE=YES
  /CRITERIA FORCEMERGE=0.05 /OUTFILE RULES='bins.sps' /PRINT ENDPOINTS ENTROPY.

statscraft help OPTIMAL BINNING prints the same text in the terminal. All commands

Statscraft 0.61.0, release v0.61.0

KNN

Nearest neighbor analysis: classify or predict a target from the k most similar training cases.

Syntax

KNN [target [(MLEVEL=S | O | N)]] [BY factors] [WITH covariates]
    [/EXCEPT VARIABLES=varlist] [/CASELABELS VARIABLE=var] [/FOCALCASES VARIABLE=var]
    [/RESCALE COVARIATE=ADJNORMALIZED | NONE] [/PARTITION TRAINING=70 HOLDOUT=30 | VARIABLE=var]
    [/MODEL [METRIC=EUCLID | CITYBLOCK] [NEIGHBORS=FIXED(K=3) | AUTO(KMIN=3, KMAX=5)]
            [FEATURES=ALL | AUTO(FORCE=varlist)]]
    [/CRITERIA [NUMFEATURES=AUTO | FIXED(n) | ERRORRATIO(MINCHANGE=0.01)] [PREDICTED=MEAN | MEDIAN]
               [WEIGHTFEATURES=NO | YES]] [/CROSSVALIDATION FOLDS=10 | VARIABLE=var]
    [/MISSING USERMISSING=EXCLUDE | INCLUDE] [/VIEWMODEL DISPLAY=YES | NO] [/PRINT CPS | NONE]
    [/SAVE [PREDVAL[(name)]] [PREDPROB[(root)]] [PARTITION[(name)]] [FOLD[(name)]] [MAXCAT(25)]]
    [/OUTFILE [MODEL='file'] [FOCALCASES='file' | dataset]].

Names and keywords are written in full, each subcommand once and never empty. Factors are coded with one 0/1 column per category seen in training; covariates are mapped onto -1 to 1 by the training minimum and maximum unless COVARIATE=NONE. Cases missing on the target or a predictor are left out (INCLUDE keeps user-missing codes of categorical ones). The rest are split at random into training and holdout cases by the TRAINING:HOLDOUT ratio (SET SEED makes it repeatable), or by VARIABLE: above 0 trains. A case’s neighbors are the k training cases closest to it by EUCLID or CITYBLOCK distance, the case itself never among them; ties keep file order. A categorical target gets the commonest neighbor category (ties: the category with more training cases, then the lower value) and probabilities (count + 1) / (k + J) over the J training categories; a scale target gets the neighbors’ MEAN or MEDIAN. NEIGHBORS=AUTO tries each k from KMIN to KMAX: by FOLDS-fold cross-validation of the training cases, or with FEATURES=AUTO by the error left after feature selection. FEATURES=AUTO starts from the FORCE list and adds, one at a time, the predictor whose model errs least, until NUMFEATURES are added (AUTO: up to 20 in all) or, with ERRORRATIO, the relative change of the error is small.

Importance: the error without the predictor plus 1/m, scaled to sum 1; WEIGHTFEATURES=YES multiplies each distance term by it. Tables: Case Processing Summary (CPS), then unless DISPLAY=NO Model Summary, the k or feature selection error log, Feature Importance, Error Summary, Classification Table, and the Nearest Neighbors and Distances of focal cases (FOCALCASES variable above 0, named by CASELABELS). SAVE adds KNN_PredictedValue, KNN_Probability_1 to _MAXCAT, KNN_Partition (1 training, 0 holdout) and KNN_Fold. OUTFILE MODEL writes a JSON model; FOCALCASES writes each focal case’s neighbors and distances. WEIGHT is ignored with a warning; SPLIT FILE gives one analysis per group.

Example

KNN plan (MLEVEL=N) BY region WITH age income /PARTITION TRAINING=8 HOLDOUT=2
  /MODEL NEIGHBORS=AUTO(KMIN=2, KMAX=6) /CROSSVALIDATION FOLDS=5 /SAVE PREDVAL PREDPROB.

statscraft help KNN prints the same text in the terminal. All commands

Statscraft 0.61.0, release v0.61.0

NAIVEBAYES

Naive Bayes classification of a categorical target, with forward selection of the predictors.

Syntax

NAIVEBAYES target [BY factors] [WITH covariates]
           [/EXCEPT VARIABLES=varlist] [/FORCE [FACTORS=varlist] [COVARIATES=varlist]]
           [/TRAININGSAMPLE PERCENT=p | VARIABLE=var]
           [/SUBSET MAXSIZE=AUTO | n [(BESTSUBSET=PSEUDOBIC | TESTDATA)] | EXACTSIZE=n | NOSELECTION]
           [/CRITERIA [BINS=10] [MEMALLOCATE=1024] [TIMER=5]] [/MISSING USERMISSING=EXCLUDE | INCLUDE]
           [/PRINT [CPS] [EXCLUDED] [SUMMARY] [SELECTED] [CLASSIFICATION] | NONE]
           [/SAVE [PREDVAL[(name)]] [PREDPROB[(root[:n])]]] [/OUTFILE MODEL='file'].

Without BY and WITH every other variable is a predictor (strings, nominal and ordinal ones as factors, scale ones as covariates), except the weight, the TRAININGSAMPLE variable and EXCEPT.

Keywords are written in full, each subcommand once. A covariate is cut into BINS intervals of equal width over the training cases, empty inner intervals merged with their neighbours. Each probability is a smoothed count: (count + 1/N) over (total + categories/N), N the training cases. Selection starts from the FORCE predictors and adds, step by step, the one that raises the mean log-likelihood of the training cases most, up to EXACTSIZE more or the MAXSIZE limit (AUTO: 20, or a fifth of the predictors when that is more, at most 100); of the subsets passed the best has the lowest pseudo-BIC (minus the mean log-likelihood plus J log(N) / 2N), or with TESTDATA the highest mean log-likelihood of the test cases (the default when TRAININGSAMPLE splits the data). NOSELECTION uses every predictor. A case is put in the target category of highest posterior probability; a missing predictor is left out of a case’s product. Cases without a target or without any predictor are left out, as are predictors that are empty or constant. PERCENT draws the training cases from the SET SEED generator; VARIABLE takes cases equal to 1. Frequency weights are rounded (below 0.5 left out). SPLIT FILE is not used.

SAVE adds PredictedValue and PredictedProbability_1 to _n (25 by default) for the first n target categories. OUTFILE MODEL writes Statscraft’s own JSON model. MEMALLOCATE and TIMER are checked; every case is kept in memory.

Example

NAIVEBAYES churn BY region plan WITH tenure spend /TRAININGSAMPLE PERCENT=70
  /SUBSET MAXSIZE=3 /CRITERIA BINS=5 /SAVE PREDVAL PREDPROB(prob).

statscraft help NAIVEBAYES prints the same text in the terminal. All commands

Statscraft 0.61.0, release v0.61.0

AIM

Attribute importance: how much each variable sets every group (cluster) apart from all cases.

Syntax

AIM groupvar [/CATEGORICAL varlist] [/CONTINUOUS varlist]
    [/CRITERIA [ADJUST=BONFERRONI | NONE] [CI=95] [HIDENOTSIG=NO | YES] [SHOWREFLINE=YES | NO]]
    [/MISSING=EXCLUDE | INCLUDE]
    [/PLOT [CATEGORY] [CLUSTER[(TYPE=BAR | PIE)]] [ERRORBAR] [IMPORTANCE[([X=GROUP | VARIABLE] [Y=TEST | PVALUE])]]].

The group variable (numeric or string) comes first; CATEGORICAL takes variables of any type, CONTINUOUS numeric ones, and at least one of them is needed. For every group and variable a test compares the group with all cases: a categorical variable by the chi-square of the group’s category counts against the shares of all cases (categories less one degrees of freedom), a continuous one by Student’s t of the group mean against the overall mean, over the group’s own standard deviation (group size less one degrees of freedom, two-sided). A group whose values are all equal gets an infinite t and significance 0. The significance level is 100 less CI percent; BONFERRONI (default) divides it by the number of groups, for the tests and for the error bar intervals. Tables: one row per variable and group with the statistic, degrees of freedom, significance and whether it passes the level. PLOT CATEGORY shows each categorical variable’s category shares within the groups, CLUSTER the size of the groups as bars or a pie, ERRORBAR the group means with their intervals, IMPORTANCE the statistics (Y=TEST) or -log10 of the significance (Y=PVALUE), one chart per variable with the groups along the axis (X=GROUP) or one per group with the variables (X=VARIABLE).

HIDENOTSIG=YES leaves out of the charts what does not pass the level; SHOWREFLINE adds the critical values, or the overall mean to the error bars. A case missing on any of the named variables is left out; INCLUDE keeps user-missing values. The weight variable is not used.

Subcommands may be given in any order; a repeated one replaces the earlier.

Example

AIM segment /CATEGORICAL region plan /CONTINUOUS spend visits
  /CRITERIA CI=90 /PLOT CLUSTER(TYPE=PIE) ERRORBAR IMPORTANCE(X=VARIABLE Y=PVALUE).

statscraft help AIM prints the same text in the terminal. All commands

Statscraft 0.61.0, release v0.61.0

SELECTPRED

Screens a long list of predictors and ranks them one by one by how well each relates to a target.

Syntax

SELECTPRED target [(MLEVEL={S | O | N})] [BY factors] [WITH covariates]
    [/EXCEPT VARIABLES=varlist]
    [/SCREENING [STATUS={ON | OFF}] [PCTMISSING=70] [PCTEQUAL=95] [PCTUNEQUAL=90] [STDDEV=0] [CV=0.001]]
    [/CRITERIA [SIZE={AUTO | n}] [PCUTOFF=0.05] [RANKING={PEARSONCHISQ | LRCHISQ | CRAMERSV | LAMBDA}]
               [TIMER=5] [SHOWUNSELECTED=0]]
    [/MISSING USERMISSING={EXCLUDE | INCLUDE}]
    [/PRINT [CPS] [EXCLUDED] [SELECTED] [SUMMARY[(PEARSONCHISQ LRCHISQ CRAMERSV LAMBDA)]] [NONE]]
    [/PLOT SUMMARY].

The target is categorical when nominal or ordinal (by MLEVEL or the dictionary), else scale.

Factors (BY) are categorical predictors, covariates (WITH, numeric) scale ones; without BY and WITH every other variable but the weight is a predictor, its kind from the dictionary, and EXCEPT leaves some out. Cases missing on the target or on every predictor are left out.

Predictors missing or constant in every case are left out, and with screening on also those with more than PCTMISSING percent missing, categorical ones with one category over PCTEQUAL percent of their cases or over PCTUNEQUAL percent of categories holding a single case, and scale ones with a standard deviation under STDDEV or an absolute coefficient of variation under CV. Each remaining predictor is tested alone on the cases valid on it and the target: with a categorical target a categorical predictor by RANKING (the Pearson or likelihood-ratio chi-square significance, or Cramer’s V or lambda, largest first), a scale one by the one-way F of the predictor across the target classes; with a scale target a categorical predictor by the F of the target across its categories and a scale one by the significance of Pearson’s r.

When both kinds are present a chi-square significance (Pearson’s unless LRCHISQ) ranks the categorical ones. Ties go to the larger statistic, then the smaller df, fewer categories or more cases, then file order. SIZE predictors are selected from the top (AUTO: the nearest whole number to the smaller of the predictor count and the larger of 30 and twice its square root), only those with a significance below PCUTOFF when significance ranks. Tables: Case Processing Summary, Excluded Predictors, Predictor Ranking (the selected ones and SHOWUNSELECTED more) and Selected Predictors; PLOT SUMMARY charts the ranking. Frequency weights are rounded, cases with a weight under 0.5 left out.

USERMISSING=INCLUDE keeps user-missing values of categorical variables. TIMER stops a run longer than that many minutes (0 for no limit). SPLIT FILE is not used. Names are written in full and each subcommand once.

Example

SELECTPRED churned BY region plan WITH spend visits tenure
  /EXCEPT VARIABLES=tenure /CRITERIA SIZE=3 RANKING=LRCHISQ /PRINT SUMMARY(CRAMERSV) /PLOT SUMMARY.

statscraft help SELECTPRED prints the same text in the terminal. All commands

Statscraft 0.61.0, release v0.61.0

RESPONSE RATE

Response rates of a numerator over a denominator in each group, with cumulative rates and limits.

Syntax

RESPONSE RATE /VARIABLES NUMERATOR=var DENOMINATOR=var GROUP=var
              [/MINRATE RATE=NONE | RATE=value | FORMULA=cost, revenue]
              [/MAXCOUNT COUNT=ALL | COUNT=n | PERCENT=value].

NUMERATOR and DENOMINATOR are numeric; GROUP is numeric or string. Both are summed within each value of GROUP, and the rate of a group is 100 times its numerator sum over its denominator sum. Groups go in ascending order of their value; the cumulative rate of a group adds up the numerator and the denominator over it and every lower group before dividing. A group whose denominator sum is 0 or below is left out, with a warning. MINRATE sets the lowest acceptable cumulative rate in percent: a value above 0 and below 100, or 100 times cost over revenue per response (both above 0). MAXCOUNT sets the highest acceptable cumulative denominator sum: a whole number, or a percentage (above 0, below 100) of the denominator total. With either limit, each table row is coloured green when it keeps every limit given (cumulative rate at least MINRATE, cumulative sum at most MAXCOUNT) and red when it does not, and the caption states the limits. Table: Response Rates, one row per group with the sums, the rate, the cumulative sums and the cumulative rate. Charts: the rates and cumulative rates by group with a line at MINRATE, and the cumulative denominator sum by group with a line at MAXCOUNT. A case missing on any of the three variables is left out; a case weight multiplies both values. /MINRATE=value and /MAXCOUNT=n are short for RATE= and COUNT=. Every word is written in full and each subcommand given once.

Example

RESPONSE RATE /VARIABLES NUMERATOR=orders DENOMINATOR=letters GROUP=area_rank
  /MINRATE FORMULA=0.6, 30 /MAXCOUNT PERCENT=50.

statscraft help RESPONSE RATE prints the same text in the terminal. All commands

Statscraft 0.61.0, release v0.61.0

ADP

Prepares a target and its inputs for modelling and writes the preparation as syntax.

Syntax

ADP /FIELDS [TARGET=var] INPUT=varlist [ANALYSISWEIGHT=var]
    [/PREPDATETIME [DATEDURATION=YES[(REFERENCE=CURRENT | YMD('y-m-d') UNIT=AUTO | YEARS | MONTHS | DAYS[(SUFFIX='s')])] | NO]
                   [TIMEDURATION=YES[(REFERENCE=CURRENT | HMS('h:m:s') UNIT=AUTO | HOURS | MINUTES | SECONDS[(SUFFIX='s')])] | NO]
                   [EXTRACTYEAR | EXTRACTMONTH | EXTRACTDAY | EXTRACTHOUR | EXTRACTMINUTE | EXTRACTSECOND=NO | YES[(SUFFIX='s')]]]
    [/SCREENING [PCTMISSING=YES[(MAXPCT=50)] | NO] [UNIQUECAT=YES[(MAXCAT=100)] | NO] [SINGLECAT=NO | YES[(MAXPCT=95)]]]
    [/ADJUSTLEVEL [INPUT=YES | NO] [TARGET=YES | NO] [MAXVALORDINAL=10] [MINVALCONTINUOUS=5]]
    [/OUTLIERHANDLING [INPUT=YES | NO] [TARGET=YES | NO] [CUTOFF=SD(3)] [REPLACEWITH=CUTOFFVALUE | MISSING]]
    [/REPLACEMISSING [INPUT=YES[(EXCLUDE([CONTINUOUS] [NOMINAL] [ORDINAL]))] | NO] [TARGET=NO | YES[(EXCLUDE(...))]]]
    [/REORDERNOMINAL [INPUT=NO | YES] [TARGET=NO | YES]]
    [/RESCALE [INPUT=ZSCORE[(MEAN=0 SD=1)] | MINMAX[(MIN=0 MAX=100)] | NONE] [TARGET=BOXCOX[(MEAN=0 SD=1)] | NONE]]
    [/TRANSFORM [MERGESUPERVISED=YES[(PVALUE=0.05)] | NO] [MERGEUNSUPERVISED=NO | YES[([ORDINAL] [NOMINAL] [MINPCT=10])]]
                [BINNING=SUPERVISED[(PVALUE=0.05)] | NONE] [SELECTION=YES[(PVALUE=0.05)] | NO] [CONSTRUCTION=YES[(ROOT=feature)] | NO]]
    [/CRITERIA SUFFIX([TARGET='_transformed'] [INPUT='_transformed'])]
    /OUTFILE PREPXML='file'.

Every word is written in full and each subcommand given once. ADP looks at the data and writes syntax (RECODE, COMPUTE, IF and VARIABLE LEVEL) that makes a prepared copy of each field it changes, named with the suffix; run that file to add the fields. The data are not changed by ADP itself, and the file holds syntax rather than XML. The steps, in order: date inputs become the time since the reference date (AUTO: days below 31 days, months of 30.4375 days below 366, else years of 365.25 days) and time inputs the time since the reference time (seconds below 60, minutes below 3600, else hours), with the parts asked for as ordinal fields; the date or time field itself is dropped. Screening drops fields with too many missing values, a single value, one dominant category or too many nominal categories. Levels: continuous fields with few values become ordinal, ordinal fields with many continuous.

Outliers of continuous fields lie more than CUTOFF robust SDs (found after setting aside thin tails of at most 5% of the cases) from the robust mean. Missing values take the mean, median or mode by level. A nominal target can be renumbered by count; a continuous target goes through Box-Cox (lambda -3 to 3 by 0.5) and then to MEAN and SD. Continuous inputs get z scores or min-max. With a target, categories of an input whose relation to the target does not differ at PVALUE are merged (F test, chi-square or the row effects test by the target’s level) and an input not related to the target is dropped; continuous inputs are binned at the Scheffe subsets of the target classes’ means for a categorical target, or dropped when their correlation with a continuous target is not significant. Without a target, MERGEUNSUPERVISED joins small neighbouring categories until each holds MINPCT of the cases. With a continuous target and CONSTRUCTION=YES the continuous inputs left are grouped by correlation (level 0.9 down to 0.2, at most five to a group) and each group is replaced by its first principal component, written as a COMPUTE into the syntax file (ROOT names them ROOT1, ROOT2, …). Frequency weights are rounded; analysis weights weigh means and spreads.

SPLIT FILE is not used. The table lists each field, its prepared field and the actions.

Example

ADP /FIELDS TARGET=churned INPUT=tenure plan region signup
  /PREPDATETIME DATEDURATION=YES(REFERENCE=YMD('2025-01-01') UNIT=MONTHS)
  /OUTFILE PREPXML='prepare.sps'.

statscraft help ADP prints the same text in the terminal. All commands

Statscraft 0.61.0, release v0.61.0

PROXIMITIES

Similarities, dissimilarities or distances between cases or variables by one of 37 measures.

Syntax

PROXIMITIES varlist | /MATRIX=IN('file' | dataset | *)
   [/VIEW=CASE | VARIABLE] [/STANDARDIZE=[VARIABLE | CASE] [NONE | Z | SD | RANGE | MAX | MEAN | RESCALE]]
   [/MEASURE=[EUCLID | SEUCLID | COSINE | CORRELATION | BLOCK | CHEBYCHEV | MINKOWSKI(p) | POWER(p,r) |
             CHISQ | PH2 | binary[(p[,np])] | NONE] [ABSOLUTE] [REVERSE] [RESCALE]]
   [/PRINT=PROXIMITIES | NONE] [/ID=var] [/MISSING=EXCLUDE | INCLUDE]
   [/MATRIX=[IN('file' | dataset | *)] [OUT('file' | dataset | *)]].

binary: the 27 binary measures of CLUSTER, from the 2 x 2 table of presence (p, default 1) and absence (np, default 0; with p alone every other value is absence). The items are the cases (VIEW=CASE, the default) or the variables. A case missing on any variable is dropped either way; the weight variable is not used. STANDARDIZE works within each variable (default) or each case before the measure: Z (the method when none is named) gives mean 0 and standard deviation 1, SD standard deviation 1, RANGE range 1, MAX largest value 1, MEAN mean 1, RESCALE values from 0 to 1; a constant set of values stays as it is, except under Z (all 0), RESCALE (all 0.5) and MEAN (plus 1). It cannot go with a binary measure. The default measure is EUCLID. ABSOLUTE drops the sign of every proximity, REVERSE changes it (a similarity becomes a dissimilarity and back) and RESCALE maps the smallest proximity to 0 and the largest to 1; they run in this order whatever the order written, on the whole matrix with its diagonal. Tables: Case Processing Summary and Proximity Matrix (left out with PRINT=NONE); a pair for which the measure is undefined is empty. ID labels the cases. MATRIX=OUT writes a matrix file that PROXIMITIES, CLUSTER, PROXSCAL and ALSCAL read with MATRIX=IN: ROWTYPE_ (PROX, with the measure and SIMILARITY or DISSIMILARITY as its value label), the ID variable, CASENO_ (the case number), VARNAME_ and one variable per item, VAR1, VAR2, … for cases and the variables’ own names for VIEW=VARIABLE; under SPLIT FILE every group adds its own matrix after the split variables. OUT(*) replaces the active dataset. MATRIX=IN reads such a file: no measure is computed from it (MEASURE and STANDARDIZE are ignored with a warning), only ABSOLUTE, REVERSE and RESCALE apply.

Example

PROXIMITIES taste aroma price /STANDARDIZE=VARIABLE RESCALE /MEASURE=BLOCK /ID=brand /MATRIX=OUT(dist).

statscraft help PROXIMITIES prints the same text in the terminal. All commands

Statscraft 0.61.0, release v0.61.0

PROXSCAL

Multidimensional scaling of one or more proximity matrices by majorization, with optimal transformations.

Syntax

PROXSCAL varlist | /MATRIX=IN('file' | dataset | *)
   [/TABLE=rowvar BY colvar [BY sourcevar] | sourcevar] [/SHAPE=LOWER | UPPER | BOTH]
   [/INITIAL=SIMPLEX | TORGERSON | RANDOM[(n)] | ('file' | dataset) [varlist]] [/WEIGHTS=varlist] [/CONDITION=MATRIX | UNCONDITIONAL]
   [/TRANSFORMATION=RATIO | INTERVAL | ORDINAL[(KEEPTIES | UNTIE)] | SPLINE [DEGREE=2] [INKNOT=1]]
   [/PROXIMITIES=DISSIMILARITIES | SIMILARITIES] [/MODEL=IDENTITY | WEIGHTED | GENERALIZED | REDUCED[(2)]]
   [/RESTRICTIONS=COORDINATES('file' | dataset) [ALL | varlist]
      | VARIABLES('file' | dataset) [ALL | FIRST(n) | varlist] [(kind ...)]]
   [/ACCELERATION=NONE] [/CRITERIA=[DIMENSIONS(2[,max])] [MAXITER(100)] [DIFFSTRESS(.0001)] [MINSTRESS(.0001)]]
   [/PRINT=[NONE] [INPUT] [RANDOM] [HISTORY] [STRESS] [DECOMPOSITION] [COMMON] [DISTANCES] [WEIGHTS]
           [INDIVIDUAL] [TRANSFORMATIONS] [VARIABLES] [CORRELATIONS]]
   [/PLOT=[NONE] [STRESS] [COMMON] [WEIGHTS] [INDIVIDUAL[(sources | ALL)]] [TRANSFORMATIONS[(sources | ALL)]]
          [RESIDUALS[(sources | ALL)]] [VARIABLES[(variables | ALL)]] [CORRELATIONS]]
   [/OUTFILE=[COMMON('file' | dataset)] [WEIGHTS(...)] [DISTANCES(...)] [TRANSFORMATIONS(...)] [VARIABLES(...)]].

The command places objects in a space so that their distances fit the transformed proximities in least squares (normalized raw stress). The proximities are dissimilarities unless PROXIMITIES=SIMILARITIES. Without TABLE each case is a row of a square matrix and each variable a column; more cases than variables hold several matrices one after the other, each a source. TABLE row BY column [BY source] reads one proximity per case, with each variable a source or the source in a third variable; TABLE=source names the matrix of each case. MATRIX=IN reads a matrix file from PROXIMITIES or CLUSTER as one source.

SHAPE=LOWER (the default) or UPPER picks a triangle; BOTH takes the weighted mean of the two. The diagonal is not used. WEIGHTS gives each proximity variable a weight variable; a missing proximity or weight counts as weight 0.

TRANSFORMATION=RATIO (the default) keeps the proximities as they are; INTERVAL is used instead, with a warning, for similarities or negative values. INTERVAL adds an intercept, ORDINAL keeps only the order (UNTIE lets ties part), and SPLINE fits a smooth rising curve of DEGREE (1 to 3) with INKNOT inner knots at quantiles, plus an intercept. CONDITION=MATRIX (the default) fits one transformation per source, UNCONDITIONAL one for all.

MODEL=IDENTITY (the default) uses one common space. WEIGHTED gives each source its own weight per dimension, GENERALIZED its own linear map of the common space and REDUCED(r) a map of rank r; one source always uses IDENTITY. INITIAL is SIMPLEX (the default), TORGERSON (classical scaling), RANDOM(n) (n random starts from the session’s generator, the best kept), or a file or dataset with one case per object holding the start coordinates (the variables named, or its first numeric ones, one per dimension, none missing). DIMENSIONS(min,max) solves from max down to min, each solution starting from the one before. Iterations stop after MAXITER, below MINSTRESS or when stress gains no more than DIFFSTRESS.

PRINT shows COMMON, WEIGHTS and STRESS by default (and VARIABLES and CORRELATIONS with RESTRICTIONS=VARIABLES). Tables: Case Processing Summary; Stress and Fit Measures (normalized raw stress, Stress-I, Stress-II, S-Stress, dispersion accounted for and Tucker’s coefficient; without STRESS only the first and the last two); Final Coordinates (COMMON); Dimension or Space Weights (WEIGHTS); Individual Space Coordinates; Distances; Transformed Proximities; Iteration History; Decomposition of Normalized Raw Stress; the proximities read (INPUT); and the Random Starts. The identity common space is turned to principal axes, and every dimension is signed so that the first object is positive.

PLOT shows COMMON and WEIGHTS by default: Common Space (a scatterplot matrix from three dimensions), Scree Plot of stress by dimensionality (STRESS), Dimension Weights, Individual Space, Transformation Plot and Residuals Plot. OUTFILE writes DIM_1, DIM_2 and so on for the common space or the weights, and OBJ_1, OBJ_2 and so on for the distances and transformed proximities, the sources one below the other.

RESTRICTIONS=COORDINATES fixes coordinates of the common space to those of a file with one case per object (the variables named, or its first numeric ones; smaller solutions use the first columns). A missing value leaves that coordinate free. The common space is not turned, so the fixed coordinates come out exactly as given, and transformed proximities and distances are shown at the scale of the file.

RESTRICTIONS=VARIABLES makes the common space a weighted sum of independent variables from a file with one case per object: the variables named, the first n, or ALL. Each variable has a kind in parentheses, one per variable or one for all: INTERVAL (the default), NOMINAL, ORDINAL with KEEPTIES or UNTIE, or SPLINE with DEGREE and INKNOT. A missing value takes the fitted value. With fewer variables than dimensions the rest are free. PRINT VARIABLES gives the transformed variables and their regression weights, CORRELATIONS their correlations with the dimensions, and OUTFILE VARIABLES writes them as VAR_1, VAR_2 and so on. PLOT CORRELATIONS (also on by default) draws each variable at its correlations with the dimensions, and PLOT VARIABLES a Transformation Plot of each variable named. Both restrictions need the identity model.

Example

PROXSCAL brand1 TO brand6 /TRANSFORMATION=ORDINAL /CRITERIA=DIMENSIONS(1,3) /PRINT=COMMON STRESS HISTORY /PLOT=COMMON STRESS.

statscraft help PROXSCAL prints the same text in the terminal. All commands

Statscraft 0.61.0, release v0.61.0

PREFSCAL

Multidimensional unfolding of preferences or proximities between row and column objects, with penalized stress.

Syntax

PREFSCAL [VARIABLES=]varlist
   [/INPUT=[ROWS(n | rowvar)] [SOURCES(n | sourcevar)]] [/PROXIMITIES=DISSIMILARITIES | SIMILARITIES]
   [/WEIGHTS=varlist] [/INITIAL=CLASSICAL[(TRIANGLE | SPEARMAN)] | CORRESPONDENCE | ROSSCLIFF
             | CENTROIDS[(n)] | RANDOM[(n)] | ('file' | dataset) [varlist]]
   [/CONDITION=ROW | MATRIX | UNCONDITIONAL]
   [/TRANSFORMATION=NONE[(INTERCEPT)] | LINEAR[(INTERCEPT)] | ORDINAL[(KEEPTIES | UNTIE)]
                    | SPLINE[([INTERCEPT] [ORDER=2] [INKNOT=1])]]
   [/MODEL=IDENTITY | WEIGHTED | GENERALIZED]
   [/RESTRICTIONS=[ROW(NONE | COORDINATES ('file' | dataset) [varlist])]
                  [COLUMN(NONE | COORDINATES ('file' | dataset) [varlist])]]
   [/PENALTY=[LAMBDA(0.5)] [OMEGA(1)]]
   [/CRITERIA=[DIMENSIONS(2[,max])] [MAXITER(5000)] [DIFFSTRESS(.000001)] [MINSTRESS(.0001)]]
   [/PRINT=[NONE] [INPUT] [MULTIPLE] [INITIAL] [HISTORY] [MEASURES] [DECOMPOSITION] [COMMON]
           [DISTANCES] [WEIGHTS] [INDIVIDUAL] [TRANSFORMATION]]
   [/PLOT=[NONE] [MULTIPLE] [INITIAL] [STRESS] [COMMON] [WEIGHTS] [INDIVIDUAL[(values)...]]
          [TRANSFORMATIONS[(values)...]] [SHEPARD[(values)...]] [FIT[(values)...]] [RESIDUALS[(values)...]]]
   [/OPTIONS=[MARKERS(var)] [COLORS(var)]]
   [/OUTFILE=[COMMON('file' | dataset)] [WEIGHTS(...)] [DISTANCES(...)] [TRANSFORMATIONS(...)]].

Each listed variable is a column object and each case a row object of a source. INPUT says how the cases form sources: ROWS(n) cases per source or SOURCES(n) sources (the cases divide evenly; both numbers take the first rows times sources cases); a row variable numbers the rows (a smaller value than the one before starts the next source), a source variable numbers the sources, which hold consecutive cases. Without INPUT there is one source. A missing proximity or a WEIGHTS value of 0 leaves the cell out; the weight variable of the data weights whole rows. SPLIT FILE is not used. Similarities are mirrored within each transformation list (largest and smallest swap).

The loss is penalized stress: the mean over transformation lists of the normalized stress, raised to LAMBDA, times the mean over lists of 1 + OMEGA v(p)^2 / v(t)^2, where v is the coefficient of variation and p and t are the proximities and transformed proximities of the list. A small LAMBDA makes the penalty stronger, OMEGA 0 turns it off. CONDITION picks the lists: every row of every source, every source, or all proximities. Each iteration moves the configuration by one majorization step and the transformation by one projected gradient step, so the penalized stress never rises. NONE keeps the proximities (INTERCEPT adds a constant), LINEAR fits a slope (INTERCEPT also a constant), ORDINAL keeps the order (UNTIE lets tied values part) and SPLINE fits a rising spline of the given degree with INKNOT inner knots; the transformed proximities are never negative. MODEL=WEIGHTED gives each source its own weight per dimension and GENERALIZED its own linear map; one source uses IDENTITY. Starts: CLASSICAL scales the full matrix after filling the row-row and column-column distances with the middle of their triangle bounds (SPEARMAN: root mean squared differences of the ranks within rows), ROSSCLIFF takes the singular vectors of the double centered squared proximities, CORRESPONDENCE the scores of a correspondence analysis of the mirrored proximities, CENTROIDS(n) the principal components of the rows with every column at the centroid of the rows that rank it among their first n, RANDOM(n) n random starts from the session’s generator, the best kept, and a file or dataset gives the coordinates of the rows, then the columns, one case per object (no missing values); its variables are the ones named, else the first MAXDIM numeric ones. RESTRICTIONS fixes the coordinates of the rows or the columns to those of such a file, one case per object of the set; a missing value leaves that coordinate free. Fixing a whole set is external unfolding. The space is then not centered, scaled or rotated, so the fixed coordinates come out as given, and restrictions go with MODEL=IDENTITY only. DIMENSIONS solves from max down to min. Iterations stop after MAXITER, at MINSTRESS, or when the penalized stress falls by no more than DIFFSTRESS times its value.

Tables: Case Processing Summary; Measures (penalized stress with its stress and penalty parts; with MEASURES also normalized stress, Kruskal’s Stress-I and II, Young’s S-Stress-I and II, dispersion and variance accounted for, recovered preference orders, the mean Spearman rho and Kendall tau-b of the rows and the coefficients of variation); Final Common Space (rows, then columns); Dimension Weights or Space Weights; and on request the proximities, Random Starts, Initial Common Space, Iteration History, Decomposition of Normalized Stress, Individual Space Coordinates, Distances and Transformed Proximities. Charts: the joint plot of the common space (OPTIONS groups the rows by the values of a variable), Dimension Weights, Individual Space, Scree Plot, Initial Common Space, Random Starts, and Transformation, Shepard, Fit and Residuals plots; the values pick rows (CONDITION=ROW) or sources by their number or identifier, ALL for all. OUTFILE writes DIM_1, DIM_2, … for the common space or the weights and ROW_1, …, COL_1, … for the distances and transformed proximities, the sources one below the other.

SMOOTH is read but runs as ORDINAL with a warning: the smoothing is not applied.

Example

PREFSCAL brand1 TO brand6 /INPUT=ROWS(person) /TRANSFORMATION=ORDINAL(UNTIE) /PRINT=MEASURES COMMON HISTORY /PLOT=COMMON TRANSFORMATIONS(1 TO 4).

statscraft help PREFSCAL prints the same text in the terminal. All commands

Statscraft 0.61.0, release v0.61.0

ALSCAL

Multidimensional scaling of proximity matrices, symmetric, asymmetric or rectangular, by alternating least squares on squared distances.

Syntax

ALSCAL VARIABLES=varlist | /MATRIX=IN('file' | dataset | *)
   [/INPUT=ROWS(ALL | n)] [/SHAPE=SYMMETRIC | ASYMMETRIC | RECTANGULAR]
   [/LEVEL=ORDINAL[([UNTIE] [SIMILAR])] | INTERVAL[(1..4)] | RATIO[(1..4)] | NOMINAL]
   [/CONDITION=MATRIX | ROW | UNCONDITIONAL] [/MODEL=EUCLID | INDSCAL | ASCAL | AINDS | GEMSCAL]
   [/CRITERIA=[NEGATIVE] [CUTOFF(0)] [CONVERGE(.001)] [ITER(30)] [STRESSMIN(.005)] [DIMENS(2[,max])] [DIRECTIONS(q)]]
   [/PRINT=[DATA] [HEADER]] [/PLOT[=DEFAULT | ALL]] [/OUTFILE='file' | dataset]
   [/FILE='file' | dataset [CONFIG | ROWCONF | COLCONF] [SUBJWGHT] [STIMWGHT] [(INITIAL)]].

Each case is a row of a square matrix of dissimilarities and each variable a column; only the triangle below the diagonal is read (SHAPE=ASYMMETRIC reads both), and more cases than variables hold one matrix per subject. With SHAPE=ASYMMETRIC the distances stay symmetric and each ordered pair of stimuli is a datum of its own: the disparities, S-stress, stress and RSQ run over all of them, a pair given in one triangle only counts once, and the start averages the two triangles.

SHAPE=RECTANGULAR (unfolding) makes the rows and the columns two sets of stimuli in one space: each case is a row of the data, the variables are its columns, INPUT=ROWS(n) takes n cases for each matrix (all cases for one matrix without it), and each value is the proximity of a row stimulus and a column stimulus, fitted to the distance between them; at least 4 rows and 4 columns. Rows and columns get coordinates of their own (Row and Column Stimulus Coordinates, the rows named Row 1, Row 2, …). The start completes each matrix with the distances of two rows and of two columns, taken midway between the bounds the triangle inequality gives from their distances to the other set, and scales that. MATRIX=IN is not read with this shape.

MATRIX=IN reads a matrix file of PROXIMITIES or CLUSTER instead, VARIABLES picking its items; a similarity file is scaled as SIMILAR, or turned into dissimilarities from its largest value for INTERVAL and RATIO. A missing value or one below CUTOFF is left out; the weight variable is not used. The model fits squared distances to squared disparities and reports S-stress, the root of the mean over the matrices of their squared misfit relative to the fourth powers of the disparities. ORDINAL keeps the order of the data (UNTIE lets ties part, SIMILAR turns the order), NOMINAL only which values are equal; INTERVAL(n) and RATIO(n) make the squared disparities a polynomial of degree n of the squared data, with and without an intercept. CONDITION=MATRIX fits each matrix on its own, UNCONDITIONAL all at once, ROW (asymmetric or rectangular data) each row of each matrix on its own, the first stimulus of an ordered pair, or the row of the data, naming its row. MODEL=INDSCAL weights the dimensions per matrix (no negative weights unless NEGATIVE). MODEL=ASCAL (SHAPE=ASYMMETRIC, 2 or more dimensions) gives every stimulus weights of the dimensions that count when it is the first of a pair, d(i,j)^2 = sum of v(i,a) (x(i,a) - x(j,a))^2, which makes the distance from i to j differ from the way back; the weights of a dimension average 1 over the stimuli, which fixes the scale of its coordinates, and the axes are not turned. MODEL=AINDS adds the subject weights of INDSCAL (more than one matrix; one matrix is fitted as ASCAL): d(i,j,k)^2 = sum of w(k,a) v(i,a) (x(i,a) - x(j,a))^2. Neither goes with CONDITION=ROW.

MODEL=GEMSCAL (more than one matrix, 2 or more dimensions) gives every matrix a metric of its own on the group space, d(i,j,k)^2 = (x(i) - x(j))’ M(k) (x(i) - x(j)), where M(k) has q directions, unit vectors of the space with a weight each: DIRECTIONS(q) of CRITERIA, at most the dimensions and by default as many. Each iteration fits the metric of a matrix by least squares and keeps its q largest eigenvalues (positive ones unless NEGATIVE); the coordinates are then turned to principal axes with a sum of squares of the number of stimuli per dimension. The Subject Weights table holds the weights of the directions and Subject Directions the directions as columns; INDSCAL is the case of the axes as directions. The start is classical scaling of the mean scalar products of all matrices, after each got the smallest constant that makes it a metric. Iterations stop when S-stress improves by less than CONVERGE, falls to STRESSMIN or after ITER; DIMENS(min,max) solves from max down to min (1 only for EUCLID), each smaller solution from the first dimensions of the one before.

Tables per dimensionality: Iteration History (S-stress and its improvement), Stress and Squared Correlation (RSQ) in Distances per matrix (Kruskal’s stress formula 1 and the squared correlation of disparities and distances, with their average), Stimulus Coordinates, for INDSCAL and AINDS Subject Weights and for ASCAL and AINDS Stimulus Weights; PRINT=DATA adds the data and the optimally scaled data, HEADER the options. The coordinates are centered; EUCLID turns them to principal axes with a mean square of 1, INDSCAL scales each dimension to a sum of squares equal to the number of stimuli (the weights the other way) and orders the dimensions by their weights; every dimension is signed so that the first stimulus is positive. PLOT gives the configuration, the subject weights, the stimulus weights, the linear fit (disparities against distances), the nonlinear fit (data against distances) for ORDINAL and NOMINAL and the transformation (data against disparities), with ALL one per matrix. OUTFILE writes TYPE_ (CON for coordinates, SUB for subject weights, STI for stimulus weights, GEM for the directions of a matrix, one row for each dimension; ROW and COL for the two sets of a rectangular matrix), DIMENS, MATNUM (0 for coordinates) and DIM1, DIM2, … for every dimensionality. FILE reads such a file (or any with TYPE_, DIM1, DIM2, …) to start the iterations from: the first rows of TYPE_ CON or ROW with a value in the last dimension, one for each stimulus, are the starting coordinates of the largest dimensionality (for a rectangular matrix the rows come as ROW or CON and the columns as COL; COLCONF is accepted with it), and with MODEL=INDSCAL or GEMSCAL (as the diagonal of the metrics) the TYPE_ SUB rows, one for each matrix, the starting weights (they are read when SUBJWGHT is listed, or when nothing is listed); with MODEL=ASCAL or AINDS the TYPE_ STI rows, one for each stimulus, start the stimulus weights (STIMWGHT, or when nothing is listed and the file has them). Each part read takes INITIAL (the default: it only starts the iterations) or FIXED in parentheses: CONFIG(FIXED) or ROWCONF(FIXED) keeps the coordinates (of the rows of a rectangular matrix), COLCONF(FIXED) those of its columns, SUBJWGHT(FIXED) the subject weights (INDSCAL and AINDS) and STIMWGHT(FIXED) the stimulus weights, and the rest is solved for them. With anything fixed the coordinates and weights are shown as the file gives them, with no centering, turning, scaling or ordering. The words may be cut to three letters.

Example

ALSCAL VARIABLES=s1 TO s9 /LEVEL=ORDINAL /CRITERIA=DIMENS(2,3) /PLOT.

statscraft help ALSCAL prints the same text in the terminal. All commands

Statscraft 0.61.0, release v0.61.0

ORTHOPLAN

Generates an orthogonal main-effects plan of profiles for a conjoint study.

Syntax

ORTHOPLAN [/FACTORS=name ['label'] [name ['label'] ...] (value ['label'] ... | 'level' ...) ...]
   [/REPLACE | /OUTFILE='file' | dataset] [/MINIMUM=n] [/HOLDOUT=n] [/MIXHOLD=YES | NO].

Builds the smallest plan in which every pair of factors is balanced against each other (the full factorial when that is smallest), with at least MINIMUM profiles when a plan of at most 81 can have them, else the largest one. A factor has 2 to 9 levels, 90 levels in all; the levels are values, each with an optional label, or quoted texts that become levels 1, 2, … with the texts as labels, and a level list serves every name written since the last list. The plan’s columns and order are random: SET SEED repeats them. HOLDOUT adds random profiles that repeat neither the plan nor each other, after the plan or, with MIXHOLD=YES, mixed into it. STATUS_ is 0 for the plan, 1 for holdouts and 2 for simulation profiles; CARD_ numbers the profiles. Without FACTORS the variables of the active dataset are the factors and their value labels the levels. Cases in the active dataset whose variables are the factors are kept after the plan as simulation profiles.

The plan replaces the active dataset with REPLACE, goes to the file or dataset of OUTFILE, and is otherwise added to the active dataset. SPLIT FILE and WEIGHT are not used. A table counts the profiles of each kind.

Example

ORTHOPLAN FACTORS=brand 'Brand' ('Acme' 'Brio' 'Cora') price 'Price' (5 '5 euro' 7 '7 euro' 9 '9 euro') organic (0 'no' 1 'yes') /HOLDOUT=2.

statscraft help ORTHOPLAN prints the same text in the terminal. All commands

Statscraft 0.61.0, release v0.61.0

PLANCARDS

Shows the profiles of a conjoint plan as a list or as one card per profile.

Syntax

PLANCARDS [/FACTORS=varlist] [/FORMAT=LIST | CARD | BOTH] [/TITLE='line' ...] [/FOOTER='line' ...]
   [/OUTFILE='file'].

Shows the profiles of the active dataset, a plan from ORTHOPLAN or typed in, with the factor and value labels: FACTORS picks the factors and their order (default every variable but STATUS_ and CARD_; string variables are allowed). LIST (default) is one table per split group, holdouts marked and simulation profiles in a table of their own; CARD is a table per experimental or holdout profile, without split groups; BOTH (or ALL) gives both. TITLE and FOOTER take one or more strings, a line each, and repeat to add lines; on cards )CARD becomes the profile’s number. OUTFILE writes the cards to a text file instead of showing them (also with BOTH; ignored with LIST).

Example

PLANCARDS /FORMAT=CARD /TITLE='Profile )CARD' /FOOTER='Your score from 0 to 10:'.

statscraft help PLANCARDS prints the same text in the terminal. All commands

Statscraft 0.61.0, release v0.61.0

CONJOINT

Part-worth utilities and importances from rankings or scores of the profiles of a plan.

Syntax

CONJOINT [PLAN=* | 'file' | dataset] [/DATA=* | 'file' | dataset] /SEQUENCE | RANK | SCORE=varlist
   [/SUBJECT=variable]
   [/FACTORS=varlist ['label'] ([DISCRETE [MORE | LESS] | LINEAR [MORE | LESS] | IDEAL | ANTIIDEAL]
             [value ['label'] ...]) ...]
   [/PRINT=ALL | ANALYSIS | SIMULATION | NONE [SUMMARYONLY]] [/UTILITY='file' | dataset]
   [/PLOT=[SUMMARY] [SUBJECT] [ALL] | NONE].

The plan (STATUS_ 0 experimental, 1 holdout, 2 simulation, the simulations last; every variable but STATUS_ and CARD_ a numeric factor) and the responses come from PLAN and DATA, one of them a file or dataset and the other by default the active dataset. The response variables follow the experimental and holdout profiles in plan order: SCORE holds scores (higher is better), RANK the rank of each profile (1 is best), SEQUENCE the profile numbers from the best down. Consecutive cases with one SUBJECT value are one subject; without SUBJECT all cases are one. A subject with a missing response is skipped. Least squares on the experimental profiles estimates per subject and for the group the utilities: DISCRETE (the default) one per level summing to 0, LINEAR the value times a coefficient, IDEAL and ANTIIDEAL a quadratic of the value; the levels of the FACTORS list replace the factor’s values from the smallest up, and labels its labels. MORE and LESS (and the quadratic models) only count subjects whose estimates go the other way. Tables: Model Description, recoded values, Cramer’s V when the plan is not orthogonal, Utilities with standard errors and the constant, Importance Values (range of a factor’s utilities as a percent of all ranges, averaged over subjects), Coefficients, Correlations (Pearson’s R and Kendall’s tau of the predicted and observed preferences, Kendall’s tau for holdouts, one-tailed), reversals, and for simulation profiles the predicted scores and the mean probabilities of maximum utility, Bradley-Terry-Luce and logit choice. PRINT picks analysis or simulation results, SUMMARYONLY drops the subjects’ tables. UTILITY writes a case per subject: split and subject variables, CONSTANT, the utilities (name1, name2, … or name_L and name_Q) and the predicted SCOREn and SIMULn. PLOT draws bar charts of the importances and utilities, SUMMARY for the group, SUBJECT per subject.

Example

CONJOINT PLAN='plan.sav' /FACTORS=price (LINEAR LESS) brand /SUBJECT=id /RANK=r1 TO r11 /PLOT=SUMMARY.

statscraft help CONJOINT prints the same text in the terminal. All commands

Statscraft 0.61.0, release v0.61.0

DISCRIMINANT

Linear discriminant analysis with direct or stepwise entry and classification of cases.

Syntax

DISCRIMINANT GROUPS=var(min,max) /VARIABLES=varlist [/SELECT=var(value)]
   [/ANALYSIS=varlist[(level)] ...] [/METHOD=DIRECT | WILKS | MAHAL | MAXMINF | MINRESID | RAO]
   [/TOLERANCE=0.001] [/MAXSTEPS=n] [/FIN=3.84] [/FOUT=2.71] [/PIN=p] [/POUT=p] [/VIN=0]
   [/FUNCTIONS=n1[,pct[,sig]]] [/PRIORS=EQUAL | SIZE | values] [/SAVE=[CLASS[=name]] [SCORES[=root]] [PROBS[=root]]]
   [/ANALYSIS=... another block] [/MISSING=EXCLUDE | INCLUDE] [/HISTORY=STEP | NONE]
   [/CLASSIFY=[NONMISSING | UNSELECTED | UNCLASSIFIED] [POOLED | SEPARATE] [MEANSUB]]
   [/STATISTICS=[MEAN] [STDDEV] [UNIVF] [COV] [CORR] [FPAIR] [BOXM] [GCOV] [TCOV] [RAW] [COEFF] [TABLE]
                [CROSSVALID] [ALL]] [/ROTATE=NONE | COEFF | STRUCTURE] [/MATRIX=IN(file | dataset | *)] [/MATRIX=OUT(file | dataset | *)] [/PLOT=[COMBINED] [SEPARATE] [MAP] [CASES[(n)]] [ALL]].

The analysis uses the cases with a whole group value in the range, no missing value on VARIABLES and, with SELECT, the selected value; groups without cases are ignored. DIRECT enters the variables that pass the tolerance; the stepwise methods enter the variable with the best criterion (smallest Wilks’ lambda, largest smallest Mahalanobis distance or F between groups, smallest sum of unexplained variation, largest increase in Rao’s V) among those passing FIN or PIN, higher inclusion levels first (even levels together, level 0 never), and remove a level 1 variable below FOUT or above POUT.

Tables: Analysis Case Processing Summary, Group Statistics, Tests of Equality of Group Means (UNIVF), Pooled Within-Groups Matrices (COV, CORR), Covariance Matrices (GCOV, TCOV), Log Determinants and Box’s M (BOXM), the stepwise tables (HISTORY), Pairwise Group Comparisons (FPAIR), Eigenvalues, Wilks’ Lambda, Standardized Canonical Discriminant Function Coefficients, Structure Matrix, Canonical Discriminant Function Coefficients (RAW), Functions at Group Centroids, Classification Processing Summary, Prior Probabilities for Groups, Classification Function Coefficients (COEFF) and Classification Results (TABLE, CROSSVALID leaving each case out). SAVE adds the predicted group, the function scores and the posterior probabilities, named DSC_m and DSCn_m unless given. Weighted when a weight variable is set. PLOT alone means COMBINED and CASES. COMBINED plots the classified cases on the first two functions by group, with the group centroids; SEPARATE makes one such plot per group; with a single function both give histograms of the scores. CASES lists every classified case (the first n) in a Casewise Statistics table: actual group, the two most likely groups with their posterior probabilities and squared distances to the centroid, the chi-square significance of the first one’s distance, and the scores (with CROSSVALID a second block repeats the cases in the analysis for the rule refitted without each). MAP splits the plane of the first two functions into the territory of each group, a convex polygon, under the pooled rule with the priors, drawn as tinted polygons with the centroids named; there is no map with one function or CLASSIFY=SEPARATE. ROTATE=COEFF or STRUCTURE adds a varimax rotation of the functions: the transformation matrix with the share of the between-groups variance of each rotated function, the rotated standardized coefficients and the rotated structure matrix; scores and classification stay as they are. MATRIX=OUT writes the group counts and means with the pooled deviations and correlations of the first analysis. MATRIX=IN reads such materials (MEAN, N or COUNT, STDDEV and CORR records): with IN(*), the active dataset being the matrix file, the analysis is made from them alone, so the tables that need cases (the case and classification summaries, classification results, CASES, PLOT of cases, SAVE, CROSSVALID) are not made, and with the pooled records the group deviations shown are the pooled ones; with the name of a file or dataset, the cases of the active dataset are classified by the functions of the matrix. With BOXM, GCOV or CLASSIFY=SEPARATE, MATRIX=OUT writes each group’s own STDDEV and CORR records (with the group value), and MATRIX=IN needs such records when one of them is given, and pooled ones when none is.

Example

DISCRIMINANT GROUPS=segment(1,3) /VARIABLES=q1 TO q6 /METHOD=WILKS /PRIORS=SIZE /STATISTICS=MEAN STDDEV UNIVF BOXM TABLE /SAVE=CLASS SCORES PROBS.

statscraft help DISCRIMINANT prints the same text in the terminal. All commands

Statscraft 0.61.0, release v0.61.0

CORRESPONDENCE

Correspondence analysis: rows and columns of a two-way table as points in a few dimensions.

Syntax

CORRESPONDENCE TABLE=rowvar(min,max) BY colvar(min,max) | ALL(rows,columns)
   [/SUPPLEMENTARY=[rowvar | ROW (values)] [colvar | COLUMN (values)]]
   [/EQUAL=[rowvar | ROW (values) (values) ...] [colvar | COLUMN (values) ...]]
   [/MEASURE=CHISQ | EUCLID] [/STANDARDIZE=RCMEAN | RMEAN | CMEAN | RSUM | CSUM]
   [/DIMENSION=2 | n] [/NORMALIZATION=SYMMETRICAL | PRINCIPAL | RPRINCIPAL | CPRINCIPAL | q]
   [/PRINT=[TABLE] [RPROFILES] [CPROFILES] [RPOINTS] [CPOINTS] [RCONF] [CCONF]
           [PERMUTATION[(n)]] [DEFAULT] [NONE]]
   [/PLOT=[BIPLOT[(len)]] [RPOINTS[(len)]] [CPOINTS[(len)]] [TRROWS[(len)]] [TRCOLUMNS[(len)]]
          [NDIM(first, last | MAX)] [NONE]]
   [/OUTFILE=[SCORE('file' | dataset)] [VARIANCE('file' | dataset)]]

Each case adds its weight (0 when negative) to one cell: every whole number in a range is a category, values are truncated to whole numbers, and a case outside a range or missing on either variable is left out. With ALL the first cases are the rows and the first variables the columns (ROWCAT_ aside, whose values and labels name the rows); a missing or negative cell counts as 0 and WEIGHT does not apply. SUPPLEMENTARY rows and columns are placed in the solution after it is found and take no part in it; each EQUAL group is added up into one category whose point all its members share. Empty rows and columns are left out. CHISQ analyzes the standardized residuals of the table; EUCLID uses STANDARDIZE: RMEAN takes out the row means, CMEAN the column means, RCMEAN both (the same as CHISQ), RSUM and CSUM first bring the row or column totals to one value. The solution has at most one dimension fewer than the smaller of the active rows and columns; the Summary lists every dimension with a singular value above 0.

NORMALIZATION q gives the row scores the power (1 + q)/2 of each singular value and the column scores (1 - q)/2; PRINCIPAL gives both the full value, which rules out the biplot. In every dimension the active row with the largest absolute score scores positive.

Tables: Summary always (singular values, inertia, the chi-square of the table with its significance, the share of the inertia of each dimension, and the standard deviation of each singular value with the correlations between them); TABLE, RPOINTS and CPOINTS without PRINT or with DEFAULT: the table with its active margins and the Overview Row and Column Points (mass, scores, inertia, each point’s share of a dimension and each dimension’s share of a point); RPROFILES and CPROFILES the profiles; RCONF and CCONF the standard deviations of the active scores and their correlations across dimensions (delta method under multinomial sampling); PERMUTATION(n) the table sorted by the scores of each of the first n dimensions (1 by default).

Plots: BIPLOT (the default) the rows and columns together, RPOINTS and CPOINTS each side alone, one chart for each pair of dimensions; TRROWS and TRCOLUMNS the scores of the categories in each dimension. NDIM(a, b) plots dimension a against a+1 to b, and the transformation plots of a to b; without it, or without values, every pair. A number after a plot keyword cuts the labels to that length (60 at most). OUTFILE SCORE writes ROWTYPE_, LEVEL_, VARNAME_ and DIM1, DIM2 and so on for every category; VARIANCE writes the covariances of the singular values (VARNAME_ SINGULAR) and of the scores of each active point outside the EQUAL groups, one case per dimension (DIMNMBR_).

Example

CORRESPONDENCE TABLE=district(1,5) BY transport(1,4) /SUPPLEMENTARY=district(5) /PRINT=DEFAULT RPROFILES RCONF /PLOT=BIPLOT.

statscraft help CORRESPONDENCE prints the same text in the terminal. All commands

Statscraft 0.61.0, release v0.61.0

MULTIPLE CORRESPONDENCE

Multiple correspondence (homogeneity) analysis: cases and categories of several nominal variables as points in a few dimensions.

Syntax

MULTIPLE CORRESPONDENCE [/VARIABLES=] varlist
   /ANALYSIS=varlist [(WEIGHT=n)] [varlist [(WEIGHT=n)] ...]
   [/DISCRETIZATION=[varlist [([GROUPING] [NCAT=7 | n] [DISTR=NORMAL | UNIFORM] | [EQINTV=width]
                               | RANKING | MULTIPLYING)] ...]]
   [/MISSING=[varlist | ALL [([PASSIVE] [MODEIMPU | EXTRACAT] | ACTIVE [MODEIMPU | EXTRACAT | RANDIMPU]
                               | LISTWISE)] ...]]
   [/SUPPLEMENTARY=[OBJECT(case numbers)] [VARIABLE(varlist)]]
   [/CONFIGURATION=[INITIAL | FIXED]('file' | dataset)] [/DIMENSION=2 | n]
   [/NORMALIZATION=VPRINCIPAL | OPRINCIPAL | SYMMETRICAL | INDEPENDENT | q]
   [/MAXITER=100 | n] [/CRITITER=.00001 | value]
   [/PRINT=[CORR] [DESCRIP[(varlist)]] [DISCRIM] [HISTORY] [OBJECT[([(labelvar)] varlist)]] [OCORR]
          [QUANT[(varlist)]] [NONE]]
   [/PLOT=[OBJECT[(varlist)][(len)]] [CATEGORY(varlist)[(len)]] [JOINTCAT[(varlist)][(len)]]
         [DISCRIM[(varlist)][(len)]] [BIPLOT[((varlist))][(varlist)][(len)]] [TRANS(var[(n)] ...)]
         [RESID(var[(n)] ...)[(len)]] [NDIM(first, last)] [NONE]]
   [/SAVE=[TRDATA[(root[(n)])]] [OBJECT[(root[(n)])]]]
   [/OUTFILE=[DISCRDATA('file' | dataset)] [TRDATA('file' | dataset)] [OBJECT('file' | dataset)]].

Each analysis variable holds categories coded 1, 2, 3 and so on; a code below 1, a system-missing and a user-missing value are missing. String values are coded in sorted order, and a numeric variable with fractions is cut into 7 groups (fewer if it has fewer values) shaped like a normal curve. DISCRETIZATION recodes on purpose, without case weights and with codes below 1 still valid: GROUPING into NCAT groups, NORMAL by the optimal cut points of a normal curve applied to z-scores, UNIFORM with counts near n/NCAT, or EQINTV bands of a given width from the smallest value; RANKING numbers the distinct values; MULTIPLYING rounds 10 times the z-score and shifts the lowest to 1. The analysis places each case (object) and each category in a few dimensions so that a category is the weighted mean of its objects and objects lie close to their own categories; the WEIGHT on ANALYSIS gives a variable more say, and WEIGHT cases count by their weight. MISSING PASSIVE (the default) leaves the variable out for that object; its MODEIMPU or EXTRACAT only fills the correlation tables. ACTIVE fills the value before the fit with the weighted mode (smallest code on ties), an extra category or a random category drawn by frequency from the session’s generator. LISTWISE drops the case. A case without any active value becomes supplementary. Supplementary objects and variables are placed after the fit.

CONFIGURATION INITIAL starts the iterations from the coordinates in a file (one variable per dimension, one case per case of the data); FIXED keeps those coordinates, standardized and made uncorrelated, and fits every analysis variable as supplementary. Without a file the start is the exact solution of the eigenproblem, so the iterations only confirm it (with more than 600 categories in all, a fixed pseudo-random start instead). DIMENSION is lowered with a warning to what the data allow. The fit stops after MAXITER iterations or when it gains less than CRITITER.

NORMALIZATION q gives the object scores the power (1 + q)/2 of each singular value (the root of the inertia) and the categories the power (1 - q)/2, both measured from the variable principal solution: VPRINCIPAL -1 (objects standard, categories at their centroids), OPRINCIPAL 1, SYMMETRICAL 0, INDEPENDENT both principal. In every dimension the object with the largest absolute score is positive. SPLIT FILE does not apply.

Tables: Case Processing Summary, Iteration History (the last step, or every step with HISTORY: variance accounted for, its increase and the loss) and Model Summary (Cronbach’s alpha, eigenvalue, inertia and percent of variance per dimension, the total and the mean) always; DESCRIP the frequencies, missing count and mode of each variable; DISCRIM the discrimination measures with the active total; CORR the correlations of the quantified variables in each dimension and OCORR of the codes, each with the eigenvalues of the active part; QUANT per variable the centroids, mass, inertia and both kinds of contributions; OBJECT the object scores (optionally labelled by a variable and with codes of others beside them) and the object contributions. Without PRINT, or with PRINT alone: DESCRIP DISCRIM CORR.

Charts (OBJECT and DISCRIM by default): objects, colored by the categories of each named variable; category points of each variable; all categories together (JOINTCAT); the discrimination measures; objects with centroids (BIPLOT, not with INDEPENDENT); quantification by code (TRANS) and quantified value against object score (RESID) for the first n dimensions.

Two dimensions give one scatter, more a scatterplot matrix, NDIM(a, b) one scatter of a against each of a+1 to b. A label length of 0 shows values and names instead of labels.

SAVE adds the quantified variables rootK_D_S (TRA by default, K the place on ANALYSIS, D the dimension, S the first free set number) and the object scores rootD_S (OBSCO), both as the normalization says; excluded cases and passive missing values are system-missing. OUTFILE writes the discretized codes (DISCRDATA, under the variables’ names), the quantified variables TRAK_D and the object scores OBSCOD.

Example

MULTIPLE CORRESPONDENCE pet garden commute /ANALYSIS=pet garden(WEIGHT=2) commute /DISCRETIZATION=commute(GROUPING NCAT=4) /MISSING=garden(ACTIVE EXTRACAT) /PRINT=DISCRIM QUANT OBJECT((household)) /PLOT=JOINTCAT /SAVE=OBJECT.

statscraft help MULTIPLE CORRESPONDENCE prints the same text in the terminal. All commands

Statscraft 0.61.0, release v0.61.0

CATPCA

Categorical principal components: quantify each variable by optimal scaling (spline, ordinal, nominal, multiple nominal or numeric) and reduce them to a few components.

Syntax

CATPCA [/VARIABLES=] varlist
   /ANALYSIS=varlist [([WEIGHT=n] [LEVEL=SPORD | SPNOM | ORDI | NOMI | MNOM | NUME]
                      [DEGREE=2 | n] [INKNOT=2 | n])] [varlist [(...)] ...]
   [/DISCRETIZATION=[varlist [([GROUPING] [NCAT=7 | n] [DISTR=NORMAL | UNIFORM] | [EQINTV=width]
                               | RANKING | MULTIPLYING)] ...]]
   [/MISSING=[varlist | ALL [([PASSIVE] [MODEIMPU | EXTRACAT | RANDIMPU]
                               | ACTIVE [MODEIMPU | EXTRACAT | RANDIMPU] | LISTWISE)] ...]]
   [/SUPPLEMENTARY=[OBJECT(case numbers)] [VARIABLE(varlist)]]
   [/CONFIGURATION=[INITIAL | FIXED]('file' | dataset)] [/DIMENSION=2 | n]
   [/NORMALIZATION=VPRINCIPAL | OPRINCIPAL | SYMMETRICAL | INDEPENDENT | q]
   [/MAXITER=100 | n] [/CRITITER=.00001 | value]
   [/ROTATION=[NOROTATE | VARIMAX | EQUAMAX | QUARTIMAX | PROMAX[(4 | kappa)] | OBLIMIN[(0 | delta)]]
              [KAISER | NOKAISER]]
   [/RESAMPLE=NONE | BOOTSTRAP[(samples=1000, percent=95, BALANCED | UNBALANCED, PROCRU | REFLEC)]]
   [/PRINT=[DESCRIP[(varlist)]] [LOADING[(SORT | NOSORT)]] [CORR] [VAF] [OCORR] [QUANT[(varlist)]]
          [HISTORY] [OBJECT[([(labelvar)] varlist)]] [NONE]]
   [/PLOT=[OBJECT[(varlist)][(len)]] [LOADING[(varlist [(CENTR[(varlist)])])][(len)]]
         [LDELLAREA[((GT|LT) (AREA|STDEV) value)]] [OBELLAREA[(...)]] [CTELLAREA[(...)]] [NELLPNT(40)]
         [CATEGORY(varlist)[(len)]] [JOINTCAT[(varlist)][(len)]] [TRANS(var[(n)] ...)[(len)]]
         [RESID(var[(n)] ...)[(len)]] [BIPLOT[(LOADING | CENTR[(varlist)])][(varlist)][(len)]]
         [TRIPLOT[(varlist[(varlist)])][(len)]] [PROJCENTR(var, varlist)[(len)]] [VAF]
         [NDIM(first, last)] [NONE]]
   [/SAVE=[TRDATA[(root[(n)])]] [OBJECT[(root[(n)])]] [APPROX[(root)]] [LDELLAREA] [CTELLAREA]
        [OBELLAREA | ELLAREAOBJ]]
   [/OUTFILE=[DISCRDATA('file' | dataset)] [TRDATA('file' | dataset)] [OBJECT('file' | dataset)]
            [APPROX('file' | dataset)] [ELLCOORD('file' | dataset)]].

The command gives each category of each variable a value (its quantification) so that a few principal components explain the quantified variables as well as they can. ANALYSIS is required and names the active variables with their options. Variables are coded as for MULTIPLE CORRESPONDENCE: whole codes from 1, lower codes and missing values missing, strings coded in sorted order, fractions cut into 7 groups unless DISCRETIZATION says otherwise. DISCRETIZATION, MISSING, SUPPLEMENTARY, CONFIGURATION, DIMENSION, MAXITER and CRITITER work as there. SPLIT FILE does not apply.

LEVEL says what the values must respect. NUME keeps equal steps between codes (all numeric gives plain principal components). ORDI keeps the order of the codes and NOMI only the grouping. SPORD (the default) and SPNOM fit a smooth spline of DEGREE pieces joined at INKNOT interior knots, placed at quantiles of the codes; SPORD keeps it rising. MNOM gives a separate value per component, the centroid of the category’s cases. WEIGHT gives a variable more say.

The fit starts from the numeric solution (iteration 0) and iterates until the variance accounted for gains less than CRITITER, at most MAXITER times. An extra category from ACTIVE EXTRACAT is free of the level’s restriction after iteration 0. The components come out on principal axes, each signed so that its positive loadings have the larger mean square. Supplementary variables are fitted to the final scores.

NORMALIZATION shares the eigenvalues between scores and loadings, so that scores times loadings stay the same. VPRINCIPAL (the default, q = -1) gives standard scores and loadings that are correlations. OPRINCIPAL (q = 1) puts the eigenvalues in the scores, SYMMETRICAL (q = 0) splits them evenly, and a number q from -1 to 1 lies between. INDEPENDENT scales the scores only. ROTATION turns the loadings of the variables that have them, and the scores and centroids with them, with Kaiser normalization unless NOKAISER.

RESAMPLE=BOOTSTRAP shows how stable the solution is: it analyses that many samples of the cases drawn with replacement (BALANCED gives every case exactly as many appearances as there are samples; UNBALANCED draws each case freely, from the generator SET SEED seeds), turns each sample’s component loadings to those of the data (PROCRU by the closest rotation, REFLEC by reflecting dimensions) and gives, for the eigenvalues, the loadings and the category values of the variables that have a single value, the value of the data, the mean and standard deviation of the samples and the percentile interval at the percent: tables Bootstrap Eigenvalues, Bootstrap Component Loadings and Bootstrap Quantifications. It cannot be combined with ROTATION or a FIXED configuration, and at least one active variable must not be MNOM. Samples that cannot be analysed are left out and counted.

The bootstrap also draws charts (unless PLOT=NONE): the eigenvalues of the data with their interval, and for a solution of 2 dimensions the confidence ellipses of the eigenvalues, of the component loadings (with LOADING), of the object points (with OBJECT) and of the category points of the variables of CATEGORY (and of all of them together with JOINTCAT); an ellipse is the region where (x - c)’ S^-1 (x - c) is at most the chi-square value of 2 degrees of freedom at the percent, around the data’s point c, S the covariance of the aligned points of the samples. LDELLAREA, OBELLAREA and CTELLAREA(GT|LT AREA|STDEV value) keep the ellipses whose area is above or below the value, or the mean area plus that many standard deviations (defaults: > AREA 0, > STDEV 2, > AREA 2); NELLPNT(n) sets the points of a contour (40). Each of those plots (loadings, objects, categories) also comes as a joint plot: the data’s labelled points together with the points the samples gave for them (at most about 200000 points of the objects, and as many of the categories, are kept: every k-th one). TRANS plots of variables with a single value show the interval of each category’s value as Lower and Upper.

With a bootstrap of 2 dimensions, SAVE LDELLAREA, CTELLAREA and OBELLAREA (also ELLAREAOBJ) add the area of every confidence ellipse as a variable named LDELL_n, CTELL_n or OBELL_n: for the objects one area per case, for the loadings the area of the k-th analysis variable in case k, for the categories the area of the k-th category (variable by variable) in case k, the other cases blank. OUTFILE ELLCOORD writes the coordinates of the ellipses drawn: Plot, Entity, Point (0 is the point of the data, then the closed contour), Dimension1 and Dimension2. Without the bootstrap the keywords warn.

Always shown: Case Processing Summary, Iteration History (iteration 0 and the last, or all with HISTORY) and Model Summary (Cronbach’s alpha, eigenvalue and percent of variance per dimension and in total). PRINT adds: DESCRIP frequencies, missing count and mode; QUANT each variable’s quantifications, centroids and vector coordinates; VAF each variable’s variance accounted for, by centroids and vectors; OCORR and CORR the correlations of the original and of the quantified variables with eigenvalues (one matrix per dimension when a variable is MNOM); OBJECT the component scores; LOADING the component loadings (SORT groups them by largest loading), with the rotated loadings, or pattern, structure and component correlations after an oblique rotation. Without PRINT, or with PRINT alone: DESCRIP LOADING CORR.

Charts (OBJECT and LOADING by default): OBJECT the component scores, colored by the categories of each named variable; LOADING the loadings, with MNOM centroids after CENTR; CATEGORY the centroids and vectors of each variable; JOINTCAT all centroids together; TRANS the quantification by code; RESID the quantified value against its approximation; BIPLOT scores with loadings or centroids and TRIPLOT with both, scaled to the loadings (not with INDEPENDENT); PROJCENTR the centroids of one variable projected on the loading directions of others (also a table); VAF bars of each variable’s variance accounted for. Two dimensions give one scatter, more give a scatterplot matrix, and NDIM(a, b) plots a against each of a+1 to b. A label length of 0 shows values and names instead of labels.

SAVE adds the quantified variables rootK_S (root TRA, K the place on ANALYSIS, S the first free set number; an MNOM variable gives rootK_D_S per dimension D, with the root cut to 3 characters), the scores rootD_S (OBSCO) and the approximations rootK_S (APP, the first score for an MNOM variable). Excluded cases and passive missing values are system-missing. OUTFILE writes the codes (DISCRDATA), TRAK or TRAK_D, OBSCOD and APPK; a file with no keyword means TRDATA.

Example

CATPCA pace crowd parking shade /ANALYSIS=pace crowd(LEVEL=ORDI) parking(LEVEL=NOMI) shade(LEVEL=SPNOM INKNOT=1) /MISSING=shade(ACTIVE EXTRACAT) /ROTATION=VARIMAX /PRINT=LOADING(SORT) VAF QUANT(parking) /PLOT=BIPLOT TRANS(shade) /SAVE=OBJECT.

statscraft help CATPCA prints the same text in the terminal. All commands

Statscraft 0.61.0, release v0.61.0

CATREG

Categorical regression: quantify a response and its predictors by optimal scaling (spline, ordinal, nominal or numeric) so that a linear model fits best, with ridge, lasso and elastic net penalties.

Syntax

CATREG VARIABLES=varlist
   /ANALYSIS=response [([LEVEL=SPORD | SPNOM | ORDI | NOMI | NUME] [DEGREE=2 | n] [INKNOT=2 | n])]
             WITH varlist [(...)] [varlist [(...)] ...]
   [/DISCRETIZATION=[varlist [([GROUPING] [NCAT=7 | n] [DISTR=NORMAL | UNIFORM] | [EQINTV=width]
                               | RANKING | MULTIPLYING)] ...]]
   [/MISSING=[varlist | ALL [(LISTWISE | MODEIMPU | EXTRACAT)] ...]]
   [/SUPPLEMENTARY=OBJECT(case numbers)]
   [/INITIAL=NUMERICAL | RANDOM | MULTISTART[(50 | threshold | ALL)]('file' | dataset)
             | FIXSIGNS(row)('file' | dataset)]
   [/MAXITER=100 | n] [/CRITITER=.00001 | value]
   [/REGULARIZATION=NONE | RIDGE[(start, stop, step)][('file')] | LASSO[(start, stop, step)][('file')]
                    | ENET[(start, stop, step)(start, stop, step)][('file')]]
   [/RESAMPLE=NONE | CROSSVAL[(10 | folds)] | BOOTSTRAP[(50 | samples)]]
   [/PRINT=[R] [COEFF] [DESCRIP[(varlist)]] [HISTORY] [ANOVA] [CORR] [OCORR] [QUANT[(varlist)]]
          [REGU] [NONE]]
   [/PLOT=[TRANS(varlist)[(len)]] [RESID(varlist)[(len)]] [REGU[(values | ALL)]]]
   [/SAVE=[TRDATA[(root)]] [PRED[(root)]] [RES[(root)]]]
   [/OUTFILE=[TRDATA('file' | dataset)] [DISCRDATA('file' | dataset)]].

The command gives each category a value (its quantification) and each predictor a coefficient so that the quantified response is predicted with the least weighted squared error; every quantified variable has mean 0 and variance 1. VARIABLES comes first and ANALYSIS is required: one response, WITH, then the predictors. Variables are coded as for CATPCA: whole codes from 1, lower codes and missing values missing, strings coded in sorted order, fractions cut into 7 groups unless DISCRETIZATION says otherwise. SPLIT FILE does not apply.

LEVEL says what the values must respect. NUME keeps equal steps (all numeric gives plain regression on standardized variables), ORDI the order of the codes and NOMI only the grouping. SPORD (the default) and SPNOM fit a spline of DEGREE (2) joined at INKNOT (2) interior knots; SPORD keeps it rising. MISSING drops cases with a gap (LISTWISE, the default) or fills the gap first with the most frequent code (MODEIMPU) or with a new code above all others (EXTRACAT, free of the level’s restriction).

Iterations stop when the error drops less than CRITITER, or after MAXITER. INITIAL=NUMERICAL (the default) first fits every variable as numeric (iteration 0 of the history); RANDOM starts at once from the standardized codes. MULTISTART tries sign patterns for the coefficients of ordinal and spline ordinal predictors: ALL of them, or those a stepwise search allows with the threshold percent (50 by default). It keeps the best and writes each pattern with its R square to the file. FIXSIGNS takes the signs from a row of such a file.

REGULARIZATION shrinks the coefficients: RIDGE divides them by 1 plus the penalty, LASSO moves them half the penalty towards 0 (stopping at 0), and ENET does both. Each penalty from start to stop by step gives a model; the default range is (0, 1, 0.02), and (0, 1, 0.1) for the ENET ridge part. With several models and neither RESAMPLE nor supplementary cases, only the REGU table and chart are shown; otherwise the model with the least prediction error is reported. RESAMPLE estimates the prediction error by K-fold cross validation (10 folds) or by the .632 bootstrap (50 samples). Supplementary cases give a test error. They get the quantifications of the active cases; a code only they have is interpolated for numeric and spline levels (and extrapolated for numeric ones), otherwise the case gets no prediction.

The Case Processing Summary is always shown. PRINT adds: DESCRIP frequencies, missing count and mode; HISTORY R square and apparent prediction error by iteration; R the Model Summary (multiple R, R square, two adjusted R squares and the prediction error); ANOVA two tables, by predictor count and by optimal scaling degrees of freedom; COEFF the coefficients with bootstrap standard errors, F tests, correlations, Pratt’s importance and tolerance; CORR and OCORR the correlations of the quantified and of the original predictors with eigenvalues; QUANT the quantification of each category; REGU per model the penalties, R square, prediction error and coefficients, also written to the REGULARIZATION file. Without PRINT, or with PRINT alone: R COEFF DESCRIP ANOVA.

Charts (none by default): TRANS the quantification by code; RESID per predictor its coefficient times quantification and the partial residuals, by code; REGU the coefficient paths against the standardized sum of coefficients (one chart per listed ridge penalty for ENET). A label length of 0 shows codes instead of labels; above 60 it is 60.

SAVE adds the quantified variables rootK_S (root TRA, K the place on ANALYSIS with the response first, S the first free set number), the predictions root_S (PRE) and the residuals root_S (RES); excluded cases are system-missing. OUTFILE writes the quantified variables TRAK (TRDATA, also a file with no keyword) and the coded variables under their names (DISCRDATA).

Example

CATREG VARIABLES=rating taste price area /ANALYSIS=rating(LEVEL=ORDI) WITH taste price(LEVEL=NUME) area(LEVEL=NOMI) /MISSING=price(MODEIMPU) /PRINT=R COEFF ANOVA QUANT(area) /PLOT=TRANS(area) /SAVE=PRED RES.

statscraft help CATREG prints the same text in the terminal. All commands

Statscraft 0.61.0, release v0.61.0

HOMALS

Homogeneity analysis in the older syntax: MULTIPLE CORRESPONDENCE with variables read as categories 1 to a stated largest value.

Syntax

HOMALS [/VARIABLES=] varlist(max) [varlist(max) ...]
   [/ANALYSIS=varlist] [/NOBSERVATIONS=n] [/DIMENSION=2 | n]
   [/MAXITER=100 | n] [/CONVERGENCE=.00001 | value]
   [/PRINT=[FREQ] [EIGEN] [DISCRIM] [QUANT] [OBJECT] [HISTORY] [DEFAULT] [ALL] [NONE]]
   [/PLOT=[NDIM(first | ALL, last | MAX)] [QUANT[(varlist)][(len)]] [OBJECT[(varlist)][(len)]]
         [DISCRIM[(len)]] [DEFAULT[(len)]] [ALL[(len)]] [NONE]]
   [/SAVE=[root][(n)]] [/MATRIX=OUT(* | 'file' | dataset)]

The number after a list is the largest category of its variables: every whole value from 1 up to it is a category, a fraction is cut to its whole part, user-missing codes count as values, and anything else (system-missing, 0, negatives, above the largest) is missing and left out of the fit for that variable. String variables are refused. ANALYSIS picks the variables of the fit (all of VARIABLES by default; named twice it is an error); the others can still label object plots.

NOBSERVATIONS uses only the first n cases. Every other subcommand counts once, the last one.

The model, the fit and the numbers are those of MULTIPLE CORRESPONDENCE with variable principal normalization, run on these categories; messages name HOMALS. Tables: Case Processing Summary, Iteration History and Model Summary (eigenvalue and inertia per dimension; the inertia is the mean discrimination measure) always; FREQ the frequencies of each variable; DISCRIM the discrimination measures; QUANT the category quantifications; OBJECT the object scores; HISTORY every iteration. Without PRINT, or with DEFAULT: FREQ EIGEN DISCRIM QUANT; ALL adds OBJECT and HISTORY. Charts (QUANT and OBJECT by default, none for one dimension): QUANT all categories together, OBJECT the objects labelled by each named variable, DISCRIM the discrimination measures. The label length lies from 1 to 20 (12 by default). NDIM(a, b) draws dimension a against a+1 to b, MAX the last dimension, ALL every pair; without it dimension 1 against 2.

SAVE adds the object scores rootD_S (HOM by default, the root cut to 6 characters, D the dimension, S the first free set number) for the first n dimensions (all by default). MATRIX=OUT writes ROWTYPE_ (QUANT), LEVEL, VARNAME_ and DIM1 to DIMn, one case per category; an asterisk replaces the active dataset. SPLIT FILE does not apply.

Example

HOMALS VARIABLES=brand(3) shop(4) payment(2) /PRINT=FREQ DISCRIM QUANT /PLOT=QUANT(5) /SAVE=hs(2).

statscraft help HOMALS prints the same text in the terminal. All commands

Statscraft 0.61.0, release v0.61.0

PRINCALS

Nonlinear principal components in the older syntax: CATPCA with variables read as categories 1 to a stated largest value.

Syntax

PRINCALS [/VARIABLES=] varlist(max) [varlist(max) ...]
   [/ANALYSIS=varlist [(ORDI | SNOM | MNOM | NUME)] [varlist [(...)] ...]]
   [/NOBSERVATIONS=n] [/DIMENSION=2 | n] [/MAXITER=100 | n] [/CONVERGENCE=.00001 | value]
   [/PRINT=[FREQ] [EIGEN] [LOADINGS] [QUANT] [HISTORY] [CORRELATION] [OBJECT] [DEFAULT] [ALL] [NONE]]
   [/PLOT=[NDIM(first | ALL, last | MAX)] [QUANT[(varlist)][(len)]] [OBJECT[(varlist)][(len)]]
         [LOADINGS[(len)]] [DEFAULT[(len)]] [ALL[(len)]] [NONE]]
   [/SAVE=[root][(n)]] [/MATRIX=OUT(* | 'file' | dataset)]

Variables are read as for HOMALS: whole values 1 to the stated largest are the categories, all else is missing. The level after a list on ANALYSIS covers the variables since the previous parenthesis: ORDI (the default) keeps the order of the categories, SNOM any values, NUME equal steps, MNOM a free point per category and dimension. The fit is that of CATPCA with these levels and variable principal normalization; messages name PRINCALS. Tables: Case Processing Summary, Iteration History and Model Summary always (the eigenvalue there is the sum over the variables; divided by their number it is the mean that older output showed); FREQ the frequencies; LOADINGS the component loadings; QUANT the quantifications with centroid and vector coordinates; CORRELATION the correlations of the quantified variables; OBJECT the object scores; HISTORY every iteration. Without PRINT: FREQ EIGEN LOADINGS; DEFAULT adds QUANT; ALL gives every one. Charts (QUANT and OBJECT by default, none for one dimension): QUANT the categories of each variable, OBJECT the objects labelled by each named variable, LOADINGS the loadings; label lengths and NDIM as for HOMALS. SAVE adds rootD_S (PRI by default). MATRIX=OUT writes ROWTYPE_ (QUANT, SCOOR_ for single and MCOOR_ for multiple coordinates, LOADING_), LEVEL, VARNAME_, VARTYPE_ (MULTIPLE, SINGLE N, ORDINAL or NUMERICAL) and DIM1 to DIMn; the quantification of a single variable is in DIM1, the other columns 0. SPLIT FILE does not apply.

Example

PRINCALS VARIABLES=taste smell(5) price(4) /ANALYSIS=taste smell(SNOM) price(NUME) /PRINT=QUANT LOADINGS /PLOT=LOADINGS.

statscraft help PRINCALS prints the same text in the terminal. All commands

Statscraft 0.61.0, release v0.61.0

OVERALS

Nonlinear canonical correlation analysis: what two or more sets of variables, each quantified at its own level, have in common.

Syntax

OVERALS [/VARIABLES=] varlist(max) [varlist(max) ...]
   /ANALYSIS=varlist [(ORDI | SNOM | MNOM | NUME)] [varlist [(...)] ...]
   /SETS=n(count, count, ...)
   [/NOBSERVATIONS=n] [/DIMENSION=2 | n] [/INITIAL=NUMERICAL | RANDOM]
   [/MAXITER=100 | n] [/CONVERGENCE=.00001 | value]
   [/PRINT=[FREQ] [QUANT] [CENTROID] [HISTORY] [WEIGHTS] [OBJECT] [FIT] [DEFAULT] [NONE]]
   [/PLOT=[NDIM(first | ALL, last | MAX)] [OBJECT[(varlist)][(len)]] [QUANT[(varlist)][(len)]]
         [LOADINGS[(len)]] [TRANS[(varlist)]] [CENTROID[(varlist)][(len)]] [DEFAULT[(len)]] [NONE]]
   [/SAVE=[root][(n)]] [/MATRIX=OUT(* | 'file' | dataset)]

Variables are read as for HOMALS and quantified at the level ANALYSIS gives (ORDI by default): MNOM a free point per category and dimension; SNOM, ORDI and NUME one value per category (free, in the order of the codes, or in equal steps) times a weight per dimension. SETS splits the ANALYSIS variables, in order, into at least two sets. A case missing on any variable of a set leaves that set out; a case in no set takes no part; each set needs three cases. The object scores and quantifications make the sum of each set’s quantified variables as close as possible to the object scores, summed over the sets; scores are centered and uncorrelated with sum of squares K times n in the metric of the number of sets each case is in. WEIGHT cases count as replications. NUMERICAL (the default) first fits every single variable as numerical and then continues at the stated levels; RANDOM starts from random scores of the session’s generator. The fit stops after MAXITER iterations or when it gains less than CONVERGENCE, and is turned to its principal axes; in each dimension the case with the largest absolute score is positive.

DIMENSION is lowered with a warning to what the sets allow. One variable per set gives the solution of HOMALS (all MNOM) or PRINCALS (all single); two sets of numerical variables give eigenvalues (1 + r)/2 for the canonical correlations r.

Tables: Variables by Set and Summary of Analysis (loss of each set per dimension over n, the mean, and the eigenvalue 1 minus the mean; the fit is their sum) always; FREQ the frequencies with the cases missing from the set; HISTORY the fit per iteration; WEIGHTS the weights and component loadings of the single variables; FIT multiple fit, single fit (squared weights) and single loss; CENTROID per variable the quantification, projected centroids and centroids; QUANT the quantification, single and multiple coordinates; OBJECT the object scores. Without PRINT, or with DEFAULT: FREQ CENTROID WEIGHTS; NONE leaves the summary. Charts (OBJECT and LOADINGS by default): object scores, labelled by each named variable; loadings; TRANS the quantification against the category (one chart per dimension for MNOM); QUANT the category coordinates; CENTROID the centroids. Label lengths and NDIM as for HOMALS. SAVE adds the object scores rootD_S (OVE by default). MATRIX=OUT writes ROWTYPE_ (QUANT, SCOOR_, MCOOR_, CENTRO_, PCENTRO_, WEIGHT_, LOADING_), LEVEL, VARNAME_, VARTYPE_, SET_ and DIM1 to DIMn; values that do not apply are 0. SPLIT FILE does not apply.

Example

OVERALS VARIABLES=habit1 habit2(4) score1 score2(10) /ANALYSIS=habit1 habit2(SNOM) score1 score2(NUME) /SETS=2(2,2) /PRINT=FIT QUANT /PLOT=OBJECT CENTROID(habit1).

statscraft help OVERALS prints the same text in the terminal. All commands

Statscraft 0.61.0, release v0.61.0

ANACOR

Correspondence analysis in the older syntax: CORRESPONDENCE with its own normalization names and defaults.

Syntax

ANACOR TABLE=rowvar(min,max) BY colvar(min,max) | ALL(rows,columns)
   [/DIMENSION=2 | n]
   [/NORMALIZATION=CANONICAL | PRINCIPAL | RPRINCIPAL | CPRINCIPAL | q]
   [/VARIANCES=[SINGULAR] [ROWS] [COLUMNS]]
   [/PRINT=[TABLE] [PROFILES] [SCORES] [CONTRIBUTIONS] [PERMUTATION] [DEFAULT] [NONE]]
   [/PLOT=[NDIM(first | ALL, last | MAX)] [ROWS[(len)]] [COLUMNS[(len)]] [JOINT[(len)]]
         [TRROWS] [TRCOLUMNS] [DEFAULT[(len)]] [NONE]]
   [/MATRIX OUT=[SCORE(* | 'file' | dataset)] [VARIANCE(* | 'file' | dataset)]]

The table is read and analyzed as CORRESPONDENCE reads it with MEASURE=CHISQ; messages name ANACOR. NORMALIZATION q gives the row scores the power (1 + q)/2 of each singular value and the column scores (1 - q)/2, q from -2 to 2: CANONICAL (or DEFAULT, the default) is 0, RPRINCIPAL 1, CPRINCIPAL -1; PRINCIPAL gives both the full value. The Summary always shows the singular values with their spread and correlations, so VARIANCES SINGULAR changes nothing; ROWS and COLUMNS add the spread and correlations of the row and column scores. PRINT: TABLE the table with its margins, PROFILES the row and column profiles, SCORES and CONTRIBUTIONS the overview of row and column points (mass, scores, inertia and both kinds of contributions), PERMUTATION the table sorted by the scores of each dimension; DEFAULT (and no PRINT) TABLE SCORES CONTRIBUTIONS.

PLOT: ROWS and COLUMNS (the default) each side alone, JOINT both together (not with PRINCIPAL), TRROWS and TRCOLUMNS the scores per category; labels are cut to 3 characters unless a length is given (20 for the transformation plots). NDIM(a, b) draws dimension a against a+1 to b, ALL every pair, MAX the last dimension; without it dimension 1 against 2. MATRIX OUT writes the scores and the variances as OUTFILE of CORRESPONDENCE does; an asterisk replaces the active dataset.

Example

ANACOR TABLE=region(1,4) BY channel(1,3) /NORMALIZATION=RPRINCIPAL /PRINT=SCORES PROFILES /PLOT=JOINT(6).

statscraft help ANACOR prints the same text in the terminal. All commands

Statscraft 0.61.0, release v0.61.0

LOGISTIC REGRESSION

Binary logistic regression with categorical covariates, stepwise selection and case diagnostics.

Syntax

LOGISTIC REGRESSION [VARIABLES=] dependent [WITH var | var BY var ...]
   [/CATEGORICAL=varlist] [/CONTRAST(var)=INDICATOR[(ref)] | DEVIATION[(ref)] | SIMPLE[(ref)] |
   DIFFERENCE | HELMERT | REPEATED | POLYNOMIAL[(metric)] | SPECIAL(matrix)]
   [/METHOD=ENTER | FSTEP[(COND | LR | WALD)] | BSTEP[(COND | LR | WALD)] [ALL | terms]] ...
   [/ORIGIN | NOORIGIN] [/ID=var] [/PRINT=[DEFAULT] [SUMMARY] [CORR] [ITER[(n)]] [GOODFIT] [CI(95)] [ALL]]
   [/CRITERIA=[BCON(0.001)] [ITERATE(20)] [LCON(0)] [PIN(0.05)] [POUT(0.10)] [EPS(1E-8)] [CUT(0.5)]]
   [/MISSING=EXCLUDE | INCLUDE] [/CASEWISE=[tempvars] [OUTLIER(2)]]
   [/SELECT=ALL | var EQ | NE | LT | LE | GT | GE value]
   [/SAVE=tempvar[(name)] ...] [/CLASSPLOT] [/EXTERNAL].

tempvar: PRED PGROUP RESID DEV LRESID SRESID ZRESID LEVER COOK DFBETA. The dependent variable has exactly two values among the cases used: the lower is coded 0 and the higher 1 (strings in alphabetical order). A case missing on any variable is left out; one missing only on the dependent still gets PRED and PGROUP. String covariates are categorical; a categorical variable with k values becomes k - 1 coded variables that enter and leave together (INDICATOR, last category as reference, by default). The fit is Newton-Raphson from all coefficients 0 and stops when no coefficient changes by BCON or more, the -2 log likelihood changes by less than LCON percent, or after ITERATE iterations. Each METHOD starts from the model the one before it left: ENTER enters its terms, FSTEP enters by the score test (PIN) and removes by the chosen statistic (POUT), BSTEP enters its terms first and then removes and enters the same way. Tables: Case Processing Summary, Dependent Variable Encoding, Categorical Variables Codings, then for block 0 and each block the Classification Table, Variables in the Equation, Variables not in the Equation, Omnibus Tests of Model Coefficients, Model Summary (-2LL, Cox and Snell and Nagelkerke R square), Model if Term Removed (LR), and with PRINT the Iteration History, Hosmer and Lemeshow Test with its contingency table, the Correlation Matrix and the intervals of Exp(B). SUMMARY shows the last step of each block only. CASEWISE lists every case, or those whose studentized residual is OUTLIER or more away from 0. SAVE adds PRE_1, PGR_1, RES_1, DEV_1, LRE_1, SRE_1, ZRE_1, LEV_1, COO_1 and DFB0_1, DFB1_1, … (one per coefficient), or the names given (DFBETA(name) gives name0, name1, …).

Weighted when a weight variable is set. CLASSPLOT gives, for every step shown, chart data of the cases counted by their predicted probability of the second category in 40 bins of 0.025, stacked by the observed category. EXTERNAL changes nothing. SELECT fits only the cases where its condition holds (the variable is numeric and none of those on VARIABLES, CATEGORICAL or METHOD; a missing value leaves the case unselected); the Case Processing Summary counts the unselected cases, the Classification Table has a part for each group, and SAVE and CASEWISE (with S or U in Selected Status) cover the unselected cases that have a prediction and an observed value.

DMLOGISTIC is another name for the command.

Example

LOGISTIC REGRESSION VARIABLES=bought WITH age income region /CATEGORICAL=region /METHOD=FSTEP(LR) /PRINT=GOODFIT CI(95) /SAVE=PRED.

statscraft help LOGISTIC REGRESSION prints the same text in the terminal. All commands

Statscraft 0.61.0, release v0.61.0

DMLOGISTIC

Another name for LOGISTIC REGRESSION.

Syntax

DMLOGISTIC dependent WITH covariates [/subcommands of LOGISTIC REGRESSION].

The same command as LOGISTIC REGRESSION, with the same subcommands and defaults.

Example

DMLOGISTIC bought WITH age tenure /PRINT=SUMMARY.

statscraft help DMLOGISTIC prints the same text in the terminal. All commands

Statscraft 0.61.0, release v0.61.0

NOMREG

Multinomial logistic regression: a nominal dependent variable on factors and covariates.

Syntax

NOMREG dependent [(BASE=FIRST | LAST | value  ORDER=ASCENDING | DATA | DESCENDING)]
   [BY factors] [WITH covariates]
   [/MODEL=[effects] [| BACKWARD | FORWARD | BSTEP | FSTEP = effects] | /FULLFACTORIAL]
   [/STEPWISE=[RULE(SINGLE | SFACTOR | CONTAINMENT | NONE)] [MINEFFECT(0)] [MAXEFFECT(n)]
              [PIN(0.05)] [POUT(0.1)] [ENTRYMETHOD(LR | SCORE)] [REMOVALMETHOD(LR | WALD)]]
   [/INTERCEPT=INCLUDE | EXCLUDE]
   [/CRITERIA=[CIN(95)] [DELTA(0)] [MXITER(100)] [MXSTEP(5)] [LCONVERGE(0)] [PCONVERGE(1E-6)]
              [SINGULAR(1E-8)] [BIAS(0)] [CHKSEP(20)]]
   [/PRINT=[CPS] [MFI] [PARAMETER] [LRT] [FIT] [SUMMARY] [CLASSTABLE] [IC] [KERNEL] [COVB] [CORB]
          [STEP] [HISTORY[(n)]] [ASSOCIATION] [CELLPROB] [NONE]]
   [/SAVE=[ESTPROB[(root[:n])]] [PREDCAT[(name)]] [PCPROB[(name)]] [ACPROB[(name)]]]
   [/SCALE=1 | n | DEVIANCE | PEARSON] [/SUBPOP=varlist] [/MISSING=EXCLUDE | INCLUDE]
   [/TEST[(constants)]=['label'] effect values ... | ALL values [; ...]] [/TEST ...].

The command fits a multinomial logistic regression: one logit for each category of a nominal dependent against a reference category. The dependent and the factors may be numeric or string; covariates are numeric. ORDER sorts the categories (ASCENDING by default; DATA keeps the order of first occurrence). BASE names the reference category (LAST by default), which has no parameters.

Without MODEL the model is the intercept, the covariates and the main effects of the factors. FULLFACTORIAL adds every interaction of the factors and cannot be given with MODEL. An effect is a factor or covariate, a*b (a BY b), a(b) (a WITHIN b) or x*x. INTERCEPT=EXCLUDE drops the intercept. A factor gets one parameter per level, an interaction one per level combination that occurs. A parameter that repeats others (by SINGULAR) is redundant and set to 0, so a factor’s last level is its reference.

A case missing on any variable, or with a weight of 0 or less, is left out; weights are not rounded. MISSING=INCLUDE treats user-missing values as valid. Cases form subpopulations by the factors and covariates, or by the SUBPOP variables, which must include every model variable. DELTA (0 to below 1) is added to a subpopulation’s empty cells and BIAS (same range) to every cell. The fit is Newton-Raphson from the intercept-only fit, with up to MXSTEP step halvings. It stops when the log likelihood changes by less than LCONVERGE, no parameter changes by PCONVERGE or more, or after MXITER iterations.

Without PRINT the output is CPS, MFI and STEP; a PRINT list replaces them, and NONE turns all off. MFI tests against the intercept-only model (without the intercept, the model of equal probabilities); IC adds AIC and BIC. SUMMARY gives the Cox and Snell, Nagelkerke and McFadden pseudo R-squares, FIT the Pearson and deviance chi-squares, LRT a likelihood ratio test of each effect, PARAMETER the estimates with Wald tests and the CIN interval of Exp(B), CLASSTABLE the classification table. The -2 log likelihoods include the multinomial constant; KERNEL leaves it out. SCALE multiplies the covariance matrix by the value, or by the Pearson or deviance chi-square over its df.

SAVE writes, for every case with valid factors and covariates, the probability of each category (ESTPROB: EST1_1, EST2_1 and so on, or root1, root2 and so on; the first n, 25 by default), the predicted category (PREDCAT: PRE_1), its probability (PCPROB: PCP_1) and the probability of the observed category (ACPROB: ACP_1).

Stepwise: the intercept and the effects before | always stay in; the method chooses among those after it. FORWARD adds, BACKWARD starts with all and drops, FSTEP adds one and then drops while it can, BSTEP starts with all, drops while it can, then adds one. The effect with the smallest p below PIN enters (likelihood ratio, or score with ENTRYMETHOD(SCORE)); the one with the largest p above POUT leaves (likelihood ratio, or Wald with REMOVALMETHOD(WALD)). A tie goes to the effect listed first. Stepping stops when nothing qualifies or a model would repeat. MAXEFFECT caps adding under FORWARD and FSTEP, MINEFFECT dropping under BACKWARD and BSTEP, not counting the intercept.

RULE(SINGLE), the default, holds an effect back until the listed effects made of part of its variables are in; SFACTOR does that only for effects of factors alone; CONTAINMENT waits for the effects it contains (same covariates, fewer factors); NONE never waits. An effect that another in the model needs is not dropped. The Step Summary lists each step with its -2 log likelihood and deciding test; the other tables describe the final model, which without the intercept can be the model of equal probabilities.

HISTORY(n) shows the -2 log likelihood and parameters of the final model at iteration 0, every n-th iteration and the last. ASSOCIATION, for a two-category response, gives Somers’ D, gamma, tau-a and C over the pairs of cases with different observed categories, compared by the predicted probability of the non-base category (rounded down to a multiple of 1/500). CELLPROB gives observed and predicted counts and proportions, with raw and standardized residuals, per subpopulation and category.

TEST tests linear combinations of the parameters. A row gives an effect and one value per parameter of it (redundant ones included, one for INTERCEPT), or ALL and a value per parameter; the two forms do not mix in one TEST. Semicolons separate rows. Constants default to 0, and a value may be a fraction. It gives a Wald chi-square per logit (df the rank of the rows) and one for all logits. TEST may be repeated.

Example

NOMREG commute (BASE=FIRST) BY district WITH distance /PRINT=PARAMETER LRT FIT SUMMARY CLASSTABLE /SAVE=ESTPROB PREDCAT.

statscraft help NOMREG prints the same text in the terminal. All commands

Statscraft 0.61.0, release v0.61.0

MVA

Missing value analysis: where values are missing, how that relates to the other variables, and estimates that allow for it.

Syntax

MVA [VARIABLES=] varlist | ALL
   [/CATEGORICAL=varlist] [/MAXCAT=25] [/ID=var]
   [/NOUNIVARIATE] [/TTEST [PERCENT=5] [T | NOT] [DF | NODF] [PROB | NOPROB] [COUNTS | NOCOUNTS]
                          [MEANS | NOMEANS]]
   [/CROSSTAB [PERCENT=5]] [/MISMATCH [PERCENT=5] [NOSORT]]
   [/DPATTERN [SORT=var[(ASCENDING | DESCENDING)] ...] [DESCRIBE=varlist]]
   [/MPATTERN [NOSORT] [DESCRIBE=varlist]] [/TPATTERN [NOSORT] [DESCRIBE=varlist] [PERCENT=1]]
   [/LISTWISE] [/PAIRWISE]
   [/EM [varlist] [WITH varlist] [(TOLERANCE=0.001 CONVERGENCE=0.0001 ITERATIONS=25
        TDF=n | LAMBDA=a PROPORTION=b, OUTFILE='file' | dataset)]]
   [/REGRESSION [varlist] [WITH varlist] [(TOLERANCE=0.001 FLIMIT=4 NPREDICTORS=n
        ADDTYPE=RESIDUAL | NORMAL | T[(5)] | NONE, OUTFILE='file' | dataset)]].

String variables and those on CATEGORICAL are categorical (a long string by its first 8 bytes); MVA stops with a warning when one has more than MAXCAT values. All others are quantitative. System-missing and user-missing values count as missing; user-missing ones are coded A, B, C in the order of their definition (a range is A, its extra value B). CATEGORICAL, MAXCAT and ID come before the other subcommands; VARIABLES, SORT, NOSORT, DESCRIBE and WITH cannot name variables here. Weights are not used.

Univariate Statistics (unless NOUNIVARIATE): valid N, missing count and percent, and for quantitative variables the mean, standard deviation and the count of extremes: values beyond 1.5 interquartile ranges outside the quartiles (at (n+1)p), or, when variables times n times log10(n) passes 150000, beyond 2 standard deviations from the mean.

TTEST: for each variable with at least PERCENT% missing, every quantitative variable is compared between the cases where it is present and missing (Welch t, its df, two-sided p with PROB, the counts and the means). CROSSTAB: per categorical variable and category, the count and percent present and the percent of each missing kind of every other variable with at least PERCENT% missing. MISMATCH: the percent of cases where one variable of a pair is missing and the other not, the percent missing on the diagonal.

DPATTERN lists every case (in file order or by SORT), MPATTERN the cases with a missing value, each with S, A, B, C for missing and + or - for extremes, the number and percent missing and the DESCRIBE values. TPATTERN counts each pattern of missing values (X), leaving out those under PERCENT% of the cases; DESCRIBE adds category counts or means. ID labels the cases. In MPATTERN, TPATTERN and MISMATCH, unless NOSORT, variables go from fewest to most missing and alike patterns stand together; DPATTERN keeps the list order.

LISTWISE: means, covariances and correlations over the cases complete on every variable.

PAIRWISE: counts, means and standard deviations of the column variable, covariances and correlations over the cases valid on both variables.

EM estimates the means, covariances and correlations of the quantitative variables (or the ones listed, from those after WITH) under a normal, a t (TDF) or a mixed normal (LAMBDA, the ratio of the standard deviations, PROPORTION, the share of the second part) distribution, starting from the univariate means and pairwise covariances; covariances divide by n - 1. It stops when no variance changes by more than CONVERGENCE relative to its value, or after ITERATIONS, and gives Little’s MCAR test. REGRESSION fills each missing value by forward stepwise regression on the predictors the case has (F to enter FLIMIT, at most NPREDICTORS), from the univariate means and pairwise covariances, plus the residual of a random complete case, a normal or t error scaled by the residual standard deviation, or nothing; NORMAL is the default when fewer than half the cases are complete. Random terms follow SET SEED. When two or more ways to estimate are shown (univariate, LISTWISE, PAIRWISE, EM, REGRESSION), summary tables compare their means and standard deviations (pairwise ones are those of all values). OUTFILE saves the active data with the missing values of the estimated variables filled in and their user-missing definitions dropped. Under SPLIT FILE each group is filled from its own estimates, all in one file; a case outside the groups that ran keeps its values, a user-missing one as system-missing.

Example

MVA VARIABLES=district mode age km minutes /CATEGORICAL=district /ID=resp /TTEST PROB /TPATTERN /EM (OUTFILE='filled.sav').

statscraft help MVA prints the same text in the terminal. All commands

Statscraft 0.61.0, release v0.61.0

HILOGLINEAR

Hierarchical loglinear models of a multiway table of counts, with backward elimination.

Syntax

HILOGLINEAR varlist (min,max) [varlist (min,max) ...]
   [/METHOD[=BACKWARD]] [/MAXORDER=k]
   [/CRITERIA=[CONVERGE(n)] [ITERATE(20)] [P(0.05)] [DELTA(0.5)] [MAXSTEPS(10)] [DEFAULT]]
   [/CWEIGHT=variable | (w w n*w ...)]
   [/PRINT=[FREQ] [RESID] [ESTIM] [ASSOCIATION] | DEFAULT | ALL | NONE]
   [/PLOT=[RESID] [NORMPROB] | DEFAULT | ALL | NONE] [/MISSING=EXCLUDE | INCLUDE]
   [/DESIGN=term [term ...]] [/DESIGN ...].

terms: a variable or variables joined by * (or BY). At least two and at most ten numeric variables, each group followed by its whole-number range; every integer of the range is a category, values are cut to integers, and a case with a value outside a range is counted as out of range and left out. A case missing on a variable is left out unless INCLUDE makes user-missing values valid; case weights are used as they are.

A DESIGN lists the generating class: the highest terms, each of which brings in all the terms made of part of its variables. Every DESIGN fits its own model with the CRITERIA, PRINT, PLOT, MAXORDER and CWEIGHT given earlier in the command (they carry over); METHOD applies to the next DESIGN only. A DESIGN with no terms, or the one added (with a warning) when the command does not end with DESIGN, is the saturated model; MAXORDER k cuts every term down to its k-variable parts. The model is fitted by iterative proportional fitting until no cell moves by CONVERGE (by default the larger of 0.25 and a thousandth of the largest weighted count) or ITERATE cycles have run. CWEIGHT gives a weight per cell, from a variable (its mean in the cell, 1 for an empty cell) or as a list in cell order with the last variable changing fastest; a weight of 0 makes a structural zero and weights are cut to the range 0 to 1.

Tables: Data Information, Convergence Information, Cell Counts and Residuals (FREQ: observed and expected counts; RESID: raw and standardized residuals) and the likelihood-ratio and Pearson Goodness-of-Fit Tests, whose df leaves out the cells fitted as 0. A saturated model is fitted to the counts plus DELTA and adds the tests that all effects of order k, or of order k and higher, are zero; ESTIM gives its effect-coded parameters with standard errors (when no cell is 0) and ASSOCIATION the partial chi-square of each lower-order term. By default an unsaturated model shows FREQ and RESID, a saturated one all four. METHOD=BACKWARD removes, one per step and at most MAXSTEPS times, the term of the generating class whose removal has the largest likelihood-ratio p, while that p is above P, and lists the steps.

PLOT (unsaturated models only) draws the standardized residuals against the observed and expected counts (RESID) and a normal Q-Q plot of the adjusted residuals (NORMPROB, also NORMPLOT); PLOT alone means both.

Example

HILOGLINEAR route(1,3) season(1,4) delay(0,1) /METHOD=BACKWARD /CRITERIA=P(0.01) /DESIGN.

statscraft help HILOGLINEAR prints the same text in the terminal. All commands

Statscraft 0.61.0, release v0.61.0

LOGLINEAR

General loglinear and logit models of a table of counts, with contrasts, cell weights and generalized residuals.

Syntax

LOGLINEAR varlist (min,max) [varlist (min,max) ...] [BY varlist (min,max) ...] [WITH covariates]
   [/CWEIGHT=variable | (w n*w ...)] [/GRESID=variable | (c n*c ...)] [/GRESID ...]
   [/CONTRAST(factor)=DEVIATION[(ref)] | DIFFERENCE | HELMERT | SIMPLE[(ref)] | REPEATED |
      POLYNOMIAL[(metric)] | [BASIS] SPECIAL(matrix)]
   [/CRITERIA=[CONVERGE(0.001)] [ITERATE(20)] [DELTA(0.5)] [DEFAULT]]
   [/PRINT=[FREQ] [RESID] [DESIGN] [ESTIM] [COR] | DEFAULT | ALL | NONE]
   [/PLOT=[RESID] [NORMPROB] | DEFAULT | ALL | NONE] [/MISSING=EXCLUDE | INCLUDE]
   [/DESIGN=effect [effect ...]] [/DESIGN ...].

effect: a factor, a covariate, factor(n) (the n-th contrast column of the factor) or effects joined by BY.

Every integer of a factor’s range is a category and the table has every combination; values are cut to integers and a case outside a range is counted and left out. A case missing on a variable is left out (INCLUDE keeps user-missing values, which the ranges must then hold); case weights are the counts. Factors after BY are the independent ones of a logit model, each combination of them a row whose total the model keeps. Cell covariates (WITH) take the weighted mean of the cases in the cell. At most 10 factors and 200 covariates.

Every DESIGN fits its own model with the CWEIGHT, GRESID, CONTRAST, CRITERIA, PRINT and PLOT given before it, which carry over to the next DESIGN; the DESIGN does not. A DESIGN without effects, or the model added when the command does not end with DESIGN (with a warning), is the saturated model of every effect, which also shows ESTIM by default. A factor of K categories gives K - 1 columns: DEVIATION (the default, the last category is the reference) estimates each category against the mean, SIMPLE against the reference, DIFFERENCE against the mean of the earlier ones, HELMERT of the later ones, REPEATED against the next, POLYNOMIAL gives orthonormal polynomials over the metric (1, 2, …, K by default); SPECIAL takes the K by K matrix transposed as the columns (its first row is the constant), BASIS SPECIAL takes the inverse (the rows are the contrasts). factor(n) is the n-th column alone and effects joined by BY are products of columns. CWEIGHT gives a weight per cell, from a variable (its mean in the cell, 1 for an empty one) or as a list in cell order with the last factor changing fastest; a weight of 0 or less makes a structural zero left out of the fit and the tables. The model is fitted by Newton-Raphson from the counts plus DELTA, which stay in the cells of a saturated model, until nothing moves by CONVERGE or ITERATE steps have run.

Tables: Data Information, Convergence Information, Cell Counts and Residuals (FREQ: observed and expected counts and percents; RESID: raw, standardized and adjusted residuals), Goodness-of-Fit Tests (likelihood ratio and Pearson, df = I (J - 1) - parameters - cells whose count times weight is 0 or less, for a table of I rows and J columns), Design Matrix (DESIGN), Parameter Estimates (ESTIM: coefficient, standard error, z and 95% interval) and the correlation of the estimates (COR, also COV), Generalized Residuals (each GRESID a linear combination of the cells: observed, expected, residual and adjusted residual), and for a logit model the Analysis of Dispersion and Measures of Association (entropy and concentration). PLOT draws adjusted residuals against the observed and expected counts (RESID) and a normal and a detrended normal plot (NORMPROB).

Example

LOGLINEAR shift(1,3) site(1,4) /CONTRAST(site)=SIMPLE(1) /PRINT=DEFAULT ESTIM /DESIGN=shift site.

statscraft help LOGLINEAR prints the same text in the terminal. All commands

Statscraft 0.61.0, release v0.61.0

GENLOG

General loglinear and logit models of a table of counts, with cell weights, covariates and contrasts.

Syntax

GENLOG factors [BY factors] [WITH covariates]
   [/CSTRUCTURE=variable] [/GRESID=varlist] [/GLOR=varlist] [/MODEL=POISSON | MULTINOMIAL]
   [/CRITERIA=[CONVERGE(0.001)] [ITERATE(20)] [DELTA(0.5)] [CIN(95)] [EPS(1E-8)] [DEFAULT]]
   [/PRINT=[FREQ] [RESID] [ZRESID] [ADJRESID] [DEV] [ITERATION] [COV] [DESIGN] [ESTIM] [CORR]
          [ALL] [DEFAULT] [NONE]]
   [/PLOT=DEFAULT | RESID[(ADJRESID DEV)] | NORMPROB[(ADJRESID DEV)] | NONE]
   [/SAVE=[RESID [(name)]] [ZRESID [(name)]] [ADJRESID [(name)]] [DEV [(name)]] [PRED [(name)]]]
   [/MISSING=EXCLUDE | INCLUDE] [/DESIGN=term [term ...]].

terms: a factor, a(n) for category n of a factor alone, a covariate, or parts joined by * or BY. Factors are numeric and their categories are the values that occur; the table has a cell for every combination, at most ten factors. The factors after BY make a logit model, which needs MULTINOMIAL. A cell’s count sums the case weights; its covariates, cell weight (CSTRUCTURE) and GRESID and GLOR coefficients are weighted means over its cases. A cell weight of 0 or less makes a structural zero, which is left out of the fit; other cell weights act as multipliers of the expected count. Without DESIGN the model is saturated, which is not allowed with covariates. Dummy coding with a constant: a factor has a column for each category, and columns that repeat earlier ones (by EPS) are redundant and 0. Under MULTINOMIAL the constant, and in a logit model the terms of the BY factors alone, only fix the totals.

Newton-Raphson starts from the counts plus DELTA (a saturated model keeps DELTA in the counts) and stops when the fitted values move by less than CONVERGE and the score is below it, or after ITERATE steps. Tables: Data Information, Model Information, Convergence Information (ITERATION adds every step), likelihood-ratio and Pearson Goodness-of-Fit Tests, Cell Counts and Residuals with the columns FREQ, RESID, ZRESID, ADJRESID and DEV ask for (FREQ, RESID, ADJRESID and DEV by default; NONE leaves the table out), the Design Matrix, Parameter Estimates with Wald z and the CIN interval (ESTIM), and their covariances (COV) and correlations (CORR). GRESID gives, for each coefficient variable, the observed and expected sums and their simple, standardized and adjusted residuals; GLOR tests each contrast of log expected counts (coefficients summing to 0, per BY combination in a logit model) with a Wald chi-square and the CIN interval. A logit model adds the analysis of dispersion with the entropy and concentration measures of association. PLOT draws adjusted (or deviance) residuals against the observed and expected counts and in normal and detrended normal plots; by default the adjusted ones in both. SAVE gives each case the value of its cell: residual (RES_n), standardized (ZRE_n), adjusted (ADJ_n), deviance (DEV_n) residual or expected count (PRE_n), or the name given.

Example

GENLOG outcome BY clinic shift /MODEL=MULTINOMIAL /PRINT=FREQ ADJRESID ESTIM /DESIGN=outcome outcome*clinic outcome*shift.

statscraft help GENLOG prints the same text in the terminal. All commands

Statscraft 0.61.0, release v0.61.0

PROBIT

Probit and logit models of response counts out of subject counts, with effective levels.

Syntax

PROBIT responses OF subjects WITH covariates [BY factor(min,max)]
   [/MODEL=PROBIT | LOGIT | BOTH] [/LOG=[base | NONE]]
   [/CRITERIA=[OPTOL(n) | CONVERGE(n)] [ITERATE(n)] [P(0.15)] [STEPLIMIT(0.1)]]
   [/NATRES[=rate]] [/PRINT=[FREQ] [CI] [RMP] [PARALL] [DEFAULT] [ALL] [NONE]]
   [/MISSING=EXCLUDE | INCLUDE].

Each case is a group of subjects: how many there were and how many responded. The chance to respond is F(a + b’x), where F is the standard normal distribution (PROBIT, the default) or the logistic one (LOGIT); BOTH fits the logit model first, then the probit one. With a factor (BY, whole-number range; cases outside it are left out) each level has its own intercept and all share the slopes. Covariates are replaced by their base 10 logarithm unless LOG says otherwise: a bare LOG means base e, NONE no transformation. A case with a covariate of 0 is a control group; under a logarithm it stays out of the fit.

NATRES adds a natural response rate c, so the chance becomes c + (1 - c) F(…): alone it is estimated (starting from the control groups’ rate, or the lowest observed rate), with a value it is fixed. Estimates are maximum likelihood by Newton steps from zero slopes, with standard errors from the observed information. More responses than subjects is an error; a case weight multiplies both counts.

Tables: Data Information, Convergence Information, Parameter Estimates (with z tests and 95% intervals), Natural Response Rate, Covariances and Correlations of Parameter Estimates and the Pearson goodness-of-fit test. PRINT left out or bare shows FREQ (observed and expected responses per case), CI (the covariate level at which each share from 0.01 to 0.99 respond, with 95% fiducial limits, on both scales under a logarithm) and RMP (the relative median potency of every pair of factor levels); PARALL tests whether the levels share the slope. CI, RMP and PARALL need a single covariate. When the goodness-of-fit test’s significance is below P the limits widen by the heterogeneity factor chi-square/df and use t instead of the normal; P(0) never does that, P(1) always. With one covariate a scatter plot shows the transformed observed rates. MISSING=INCLUDE keeps user-missing values.

Example

PROBIT hatched OF eggs BY strain(1,3) WITH dose /MODEL=BOTH /PRINT=ALL.

statscraft help PROBIT prints the same text in the terminal. All commands

Statscraft 0.61.0, release v0.61.0

CURVEFIT

Fit up to eleven curves of one independent variable, or of time, by least squares.

Syntax

CURVEFIT [VARIABLES=] dependents [WITH independent]
   [/MODEL=[LINEAR] [LOGARITHMIC] [INVERSE] [QUADRATIC] [CUBIC] [COMPOUND] [POWER] [S]
          [GROWTH] [EXPONENTIAL] [LGSTIC] [ALL]]
   [/CONSTANT | /NOCONSTANT] [/UPPERBOUND=NO | n] [/CIN=95] [/PRINT=ANOVA]
   [/SAVE=[PRED] [RESID] [CIN]] [/PLOT=FIT | NONE] [/ID=variable] [/TEMPLATE='file']
   [/APPLY[='model name'] [SPECIFICATIONS | FIT]].

Model names may be cut to three letters. With x the independent (or 1, 2, 3, … in case order when there is no WITH): LINEAR b0 + b1 x, LOGARITHMIC b0 + b1 ln x, INVERSE b0 + b1/x, QUADRATIC and CUBIC add x^2 and x^3, COMPOUND b0 b1^x, POWER b0 x^b1, S exp(b0 + b1/x), GROWTH exp(b0 + b1 x), EXPONENTIAL b0 exp(b1 x), LGSTIC 1 / (1/u + b0 b1^x) with u from UPPERBOUND (no bound: 1/u is 0). The last six are fitted on the log scale, so they need every dependent value above 0 (and below u); their b0 and multiplicative b1 come back from the logarithm, with standard errors scaled the same way. NOCONSTANT drops b0. LINEAR is the default. A case missing on any named variable is left out of every fit; user-missing values count as missing unless TSET MISSING=INCLUDE. Case weights apply only when there is an independent variable. CIN, CONSTANT or NOCONSTANT and ID default to their TSET settings, and TSET TOLER is the tolerance QUADRATIC and CUBIC need.

Each dependent gets a Model Summary and Parameter Estimates table: R square, F, df and its significance and the estimates of every model. PRINT=ANOVA adds per model the summary, the analysis of variance and the coefficients with t tests. SAVE adds per dependent and model FIT_n (PRED), ERR_n (RESID, in the original units) and LCL_n and UCL_n (CIN: a prediction interval at the CIN level), n the first number free for all of them; fits and intervals are also given for cases with only the dependent missing. Without SAVE, TSET NEWVAR decides: CURRENT (the default) saves all four, numbered from 1 in the order of dependents and models and replacing variables of those names; ALL saves them under free numbers; NONE saves none. PLOT=FIT (the default) gives a chart of the observed values with every fitted curve; ID labels its points. Another subcommand given twice keeps the last. TEMPLATE is ignored. APPLY runs the previous CURVEFIT’s specifications again: the dependents and the independent of the new command when it names some, else the old ones, and any subcommand it gives replaces the old one (SAVE is not carried over); APPLY can also name the model named in quotes (MOD_1, MOD_2, … in the order the session made them). APPLY FIT keeps the estimates of that earlier fit: the tables are the original ones, while the plot and the saved variables put its coefficients to use on the current data, with the original error variance and degrees of freedom for the limits; a model the earlier command did not fit is left out with a warning.

Example

CURVEFIT VARIABLES=visitors WITH week /MODEL=LINEAR QUADRATIC GROWTH /PRINT=ANOVA /SAVE=PRED CIN.

statscraft help CURVEFIT prints the same text in the terminal. All commands

Statscraft 0.61.0, release v0.61.0

WLS

Weighted least squares: weights from a power of a source variable, or a given weight.

Syntax

WLS [VARIABLES=] dependent WITH independents
   [/SOURCE=variable] [/DELTA=powers] [/WEIGHT=variable] [/CONSTANT | /NOCONSTANT]
   [/PRINT=BEST | ALL] [/SAVE=WEIGHT] [/APPLY].

Powers: numbers and grids first TO last BY step (or first BY step TO last), at most 150 in all; POWER is another name for DELTA and every DELTA counts. A case’s weight is its SOURCE value raised to minus the power. SOURCE defaults to the first independent and the power to 1; with neither SOURCE, DELTA nor WEIGHT a warning says so. Powers are kept within -6.5 and 7.5, and cases whose source is not above 0 are left out. WEIGHT names a variable that holds the weights instead (cases with a weight not above 0 are left out); it cannot go with SOURCE or DELTA. A case missing on any named variable is left out; case weights (WEIGHT command) multiply the regression weights and count as cases.

For every power the log-likelihood is 0.5 (-n ln 2 pi - n ln s^2 + sum ln w - (n - p)), with s^2 the weighted mean square error and p the number of coefficients; the Log-Likelihood Values table lists it and the power with the largest one is used. For that power (or for the WEIGHT variable) come the Model Summary (R, R square, adjusted R square, standard error and log-likelihood), ANOVA and Coefficients (B, standard error, standardized Beta with its standard error, t and significance). PRINT=ALL adds the coefficients of every power; without PRINT, TSET PRINT=DETAILED does the same and BRIEF leaves out the log-likelihoods.

SAVE=WEIGHT keeps the chosen weights as WGT_n, the first free n. Without SAVE, TSET NEWVAR decides: CURRENT (the default) saves WGT_1, replacing it, ALL the next free WGT_n, NONE nothing. CONSTANT or NOCONSTANT defaults to TSET. APPLY runs the previous WLS’s specifications again: the variables of the new command when it names some, else the old ones, and any subcommand it gives replaces the old one (a WEIGHT replaces SOURCE and DELTA and the other way round; SAVE is not carried over); APPLY can also name the model named in quotes (MOD_1, MOD_2, … in the order the session made them).

Example

WLS rent WITH floor_area rooms /SOURCE=floor_area /POWER=-1 TO 3 BY 0.25 /PRINT=ALL.

statscraft help WLS prints the same text in the terminal. All commands

Statscraft 0.61.0, release v0.61.0

MODEL PROGRAM

Name the parameters of a nonlinear model and give their starting values; the transformations after it define the model.

Syntax

MODEL PROGRAM parameter[=value] [[,] parameter[=value] ...].

The transformations that follow (COMPUTE, IF, RECODE, DO IF, LOOP and the like), up to the next command of another kind, are kept for the next NLR instead of changing the data. They compute the predicted value of the dependent variable from the parameters and the variables of the data, into the variable PRED unless the PRED subcommand of NLR names another. Every parameter is named once and needs a starting value, here or from the FILE of NLR; a value of zero says nothing about the scale of the parameter, so avoid it. VARIABLE LABELS and FORMATS for the predicted values may stand among the transformations. The model program changes neither the data nor the variables: its parameters and the variables it creates exist only while NLR runs.

DERIVATIVES. inside the program starts the derivatives program, whose COMPUTE commands give the derivative of the predicted value for a parameter in the variable D.parameter; a derivative it leaves out is estimated numerically. A model program stays until an NLR uses it, CLEAR MODEL PROGRAMS, NEW FILE, CLEAR TRANSFORMATIONS or the next MODEL PROGRAM.

Example

MODEL PROGRAM b0=2 b1=0.3.
COMPUTE pred = b0 * EXP(b1 * dose).

statscraft help MODEL PROGRAM prints the same text in the terminal. All commands

Statscraft 0.61.0, release v0.61.0

DERIVATIVES

Start the derivatives program of the model program.

Syntax

DERIVATIVES.

The transformations that follow, up to the next command of another kind, compute derivatives of the predicted value of the model for NLR. Name the derivative of a parameter D.parameter, for example D.b1 for b1. The commands may use the parameters, the variables of the data, the variables of the model program and the derivatives computed before. Give the derivatives of some of the parameters or of all; NLR estimates the others numerically and, at the start, compares the derivatives given with numerical ones (CKDER of CRITERIA).

Example

DERIVATIVES.
COMPUTE D.b0 = EXP(b1 * dose).
COMPUTE D.b1 = b0 * dose * D.b0.

statscraft help DERIVATIVES prints the same text in the terminal. All commands

Statscraft 0.61.0, release v0.61.0

CLEAR MODEL PROGRAMS

Drop the model program and the derivatives program of the last MODEL PROGRAM.

Syntax

CLEAR MODEL PROGRAMS.

The model program and the derivatives program are dropped, so a new MODEL PROGRAM can start afresh. NLR uses its programs up when it runs.

Example

CLEAR MODEL PROGRAMS.

statscraft help CLEAR MODEL PROGRAMS prints the same text in the terminal. All commands

Statscraft 0.61.0, release v0.61.0

NLR

Nonlinear regression by least squares (Levenberg-Marquardt) for the model of the last MODEL PROGRAM.

Syntax

NLR dependent
   [/FILE=file] [/OUTFILE=file] [/PRED=variable]
   [/SAVE=[PRED] [RESID[(variable)]] [DERIVATIVES]]
   [/CRITERIA=[ITER(100 per parameter)] [CKDER(0.5)] [SSCON(1E-8)] [PCON(1E-8)] [RCON(1E-8)]]

Fits the model defined by MODEL PROGRAM (and DERIVATIVES) to the dependent variable by minimizing the sum of squared residuals, weighted by the case weights (which are not case replicates here: the degrees of freedom count the cases). The tables are the iteration history (the residual sum of squares and the parameters at each iteration), the analysis of variance (regression, residual, uncorrected total, corrected total) with R squared, the parameter estimates with asymptotic standard errors and 95% confidence intervals, and the asymptotic correlations of the estimates.

The iterations stop when a step lowers the sum of squares by a proportion of at most SSCON, when no parameter changes by more than the proportion PCON, when the correlation of every derivative with the residuals is at most RCON, or after ITER iterations (a warning); 0 switches a criterion off. FILE reads starting values from a data file that an earlier OUTFILE wrote, for the parameters the MODEL PROGRAM names without a value (a value given there wins); with SPLIT FILE its cases go to the groups in order, the last one to every group after it. OUTFILE writes the split variables, the parameters, SSE (the residual sum of squares) and NCASES, one case per group. SAVE appends the predicted values, the residuals (named in parentheses, else RESID or what the keyword was written as) and the derivatives D.parameter (the first six letters of the parameter name) to the data, the predicted values with the label and format the model program gave them, the others with that format; a variable whose name is taken is not saved. A case whose dependent variable, weight or predicted value is missing, or whose weight is zero or negative, is left out.

Example

MODEL PROGRAM b0=2 b1=0.3.
COMPUTE pred = b0 * EXP(b1 * dose).
NLR response.

statscraft help NLR prints the same text in the terminal. All commands

Statscraft 0.61.0, release v0.61.0

CONSTRAINED FUNCTIONS

Start the program that computes the constrained functions of the next CNLR.

Syntax

CONSTRAINED FUNCTIONS.

The transformations that follow, up to the next command of another kind, compute functions of the parameters of the MODEL PROGRAM, each into a variable, for the bounds of the next CNLR (a bound such as cf <= 0 names the variable). The program belongs right before CNLR; NLR refuses it. A constrained function may depend on the parameters only: its value is taken from the first case that is used, and a function that differs between cases is an error.

Example

CONSTRAINED FUNCTIONS.
COMPUTE cf = b0 - EXP(b1).

statscraft help CONSTRAINED FUNCTIONS prints the same text in the terminal. All commands

Statscraft 0.61.0, release v0.61.0

CNLR

Constrained nonlinear regression: least squares or a loss function of your own, under bounds, linear constraints and constrained functions.

Syntax

CNLR dependent
   [/FILE=file] [/OUTFILE=file] [/PRED=variable]
   [/SAVE=[PRED] [RESID[(variable)]] [DERIVATIVES] [LOSS]]
   [/BOUNDS=bound; bound; ...] [/LOSS=variable] [/BOOTSTRAP[(samples)]]
   [/CRITERIA=[ITER(n)] [MINORITERATION(n)] [CRSHTOL(0.01)] [STEPLIMIT(2)] [FTOLERANCE(n)]
   [LFTOLERANCE(n)] [NFTOLERANCE(n)] [LSTOLERANCE(0.9)] [OPTOLERANCE(n)] [FPRECISION(n)]
   [ISTEP(1E20)] [CKDER(0.5)]]

Fits the model of MODEL PROGRAM (and DERIVATIVES) like NLR, but by a method that allows constraints. FILE, OUTFILE, PRED, SAVE and the check of the derivatives work as in NLR; SAVE LOSS also saves the loss variable. A bound is two or three linear forms (numbers, parameters and number * parameter, joined by + and -) with =, EQ, <=, LE, >= or GE between them; two relations point the same way, as in 2 <= b <= 5. A bound on one parameter limits it, a bound on several is a linear constraint; both hold at every trial value of the parameters, which start at the nearest point that meets them. A bound that names the variable of a CONSTRAINED FUNCTIONS program is nonlinear: the variable stands alone against a number, and the bound is met at the solution. Without LOSS the sum of weighted squared residuals is minimized and the tables of NLR follow (their standard errors take no account of the bounds). LOSS names a variable of the model program that holds the loss of a case; the weighted sum of it is minimized, derivatives in the DERIVATIVES program are then those of the loss, and only the iteration history with the final estimates is shown. BOOTSTRAP re-estimates the model on samples drawn from the cases with replacement (10 p (p + 1) / 2 of them unless a number is given, p the parameters) and shows the bootstrap standard errors, the 95% trimmed range and the correlations of the estimates; OUTFILE then gets the case of the estimates followed by one case per sample, NCASES counting the distinct cases drawn. ITER limits the iterations in all, MINORITERATION those of one inner minimization; CRSHTOL moves a starting value that lies within that relative distance of a bound onto it; STEPLIMIT limits the length of a step to that multiple of the length of the parameters (at least 1); FTOLERANCE, LFTOLERANCE and NFTOLERANCE say how far a constraint may be missed (all, linear and nonlinear ones); LSTOLERANCE is the accuracy of the line search, a smaller value being more exact; OPTOLERANCE and FPRECISION end the iterations when the gradient on the free parameters is at most the square root of the larger of the two times one plus the objective; a step longer than ISTEP stops the run as unbounded.

Example

MODEL PROGRAM b0=2 b1=0.3.
COMPUTE pred = b0 * EXP(b1 * dose).
CNLR response /BOUNDS 0 <= b1 <= 1; b0 + b1 <= 5.

statscraft help CNLR prints the same text in the terminal. All commands

Statscraft 0.61.0, release v0.61.0

MULTIPLE IMPUTATION

Multiple imputation: several completed copies of the data with plausible values in place of the missing ones.

Syntax

MULTIPLE IMPUTATION varlist
   [/IMPUTE [METHOD=AUTO | FCS | MONOTONE | NONE] [NIMPUTATIONS=5] [SCALEMODEL=LINEAR | PMM[(5)]]
           [INTERACTIONS=NONE | TWOWAY] [MAXPCTMISSING=NONE | pct] [MAXCASEDRAWS=50]
           [MAXPARAMDRAWS=2] [MAXITER=10] [SINGULAR=1E-12] [MAXMODELPARAM=100]]
   [/CONSTRAINTS varlist ([MIN=NONE | value] [MAX=NONE | value] [RND=NO | step]
                          [ROLE=BOTH | DEP | IND])] ...
   [/MISSINGSUMMARIES [OVERALL] [VARIABLES[(MAXVARS=25 MINPCTMISSING=10)]] [PATTERNS] | NONE]
   [/IMPUTATIONSUMMARIES [MODELS] [DESCRIPTIVES[(varlist)]] | NONE]
   [/ANALYSISWEIGHT var]
   [/OUTFILE [IMPUTATIONS='file' | dataset] [FCSITERATIONS='file' | dataset]].

Fills in the missing values of the listed variables several times over and writes every completed copy, stacked under the original cases, to IMPUTATIONS (needed unless METHOD=NONE).

The new first variable Imputation_ is 0 for the original cases and 1 to n for the copies, and the new data are split by it. Keywords are written in full and their equals signs are needed.

Each variable is imputed from the others by its own model: linear regression for a scale variable (PMM instead takes the observed value of one of the k cases whose predictions lie nearest), multinomial logistic regression for a nominal, ordinal or string one; model parameters are drawn from their posterior first, so the copies differ. Categorical predictors enter as indicators, with TWOWAY also their pairwise products. MONOTONE imputes once in list order, each variable from the ones before it, and needs a monotone pattern of missing values; FCS starts from random values and cycles through the variables MAXITER times, each one from all the others; AUTO orders the variables from fewest to most missing, takes MONOTONE when the pattern allows it and FCS (10 rounds, linear, main effects) otherwise. A variable with more than MAXPCTMISSING percent missing is left out. CONSTRAINTS: MIN and MAX bound linear imputations (a value outside is drawn again, up to MAXCASEDRAWS times, then the parameters, up to MAXPARAMDRAWS times), RND rounds them to a multiple, ROLE=DEP imputes without predicting and ROLE=IND predicts and is imputed only for that. User-missing and system-missing values are both filled; cases with nothing valid, a weight under 0.5 or an ANALYSISWEIGHT of 0 or less keep theirs. WEIGHT counts cases (rounded); ANALYSISWEIGHT weights the models. Random draws follow SET SEED and SET RNG. FCSITERATIONS saves the mean and standard deviation of the imputed values of each scale variable after every round.

Tables: the overall missing summary, VARIABLES (the most missing first, at least MINPCTMISSING percent), PATTERNS, the specifications, constraints and results, MODELS and DESCRIPTIVES of the original, imputed and completed values. A summary subcommand shows only the keywords on it.

Pooling: with the data split by Imputation_, DESCRIPTIVES adds a table of pooled means by Rubin’s rules (standard error, df, 95% interval, fraction of missing information, relative increase in variance, relative efficiency) and FREQUENCIES a table of the frequencies and percents averaged over the imputations. MEANS pools the mean of every row of its reports, T-TEST the mean differences, CORRELATIONS each correlation (on Fisher’s z scale), REGRESSION, LOGISTIC REGRESSION, PLUM and NOMREG the coefficients; REGRESSION and LOGISTIC REGRESSION also get an F test that all their slopes are 0, pooled from the covariance matrices of the coefficients (Li, Raghunathan and Rubin 1991). SET MIOUTPUT chooses which of the original, imputed and pooled results appear and whether the pooling diagnostics do.

Example

MULTIPLE IMPUTATION rent hhsize tenure commute /IMPUTE METHOD=FCS NIMPUTATIONS=10 /CONSTRAINTS hhsize (MIN=1 RND=1) /OUTFILE IMPUTATIONS='filled.sav'.

statscraft help MULTIPLE IMPUTATION prints the same text in the terminal. All commands

Statscraft 0.61.0, release v0.61.0

PLUM

Ordinal regression: a cumulative link model of an ordered dependent variable.

Syntax

PLUM dependent [BY factors] [WITH covariates]
   [/LINK=LOGIT | PROBIT | CLOGLOG | NLOGLOG | CAUCHIT] [/LOCATION=effects] [/SCALE=effects]
   [/CRITERIA=[CIN(95)] [DELTA(0)] [BIAS(0)] [MXITER(100)] [MXSTEP(5)] [LCONVERGE(0)]
              [PCONVERGE(1E-6)] [SINGULAR(1E-8)]] [/MISSING=EXCLUDE | INCLUDE]
   [/PRINT=[FIT] [SUMMARY] [PARAMETER] [TPARALLEL] [CELLINFO] [COVB] [CORB] [HISTORY[(n)]] [KERNEL]]
   [/SAVE=[ESTPROB[(root[:n])]] [PREDCAT[(name)]] [PCPROB[(name)]] [ACPROB[(name)]]]
   [/TEST[(constants)]=['label'] effect values ...; ... | ALL values ...] ...

The values of the dependent, sorted ascending (numbers or strings), are the ordered categories. Factors may be strings; covariates are numeric. A case missing on any variable is left out (INCLUDE keeps user-missing values); the weight is rounded to a whole number and a case below 1 after rounding is left out. The model puts the link of the probability of each category or a lower one equal to its threshold minus the location effects, divided by exp of the scale effects. LOCATION defaults to the covariates and then the main effect of each factor; effects are written as in UNIANOVA (a*b, a BY b, a(b), a WITHIN b, x*x), and INTERCEPT alone leaves only the thresholds. A factor has one parameter per level that occurs; the last is redundant and 0. The cases are pooled by their factor levels and covariate values: DELTA goes into each empty cell of such a group, BIAS into every cell. The fit is Newton-Raphson from thresholds at the cumulative shares of the categories and the other parameters 0 (the location part first when SCALE is given), each step halved up to MXSTEP times while the log likelihood would fall; it stops when no parameter moves PCONVERGE or more, the log likelihood changes less than LCONVERGE (absolute or relative), or after MXITER iterations.

Tables: Case Processing Summary and Model Fitting Information (-2 log likelihood of the thresholds alone and of the final model, their difference as a chi-square) always; Goodness-of-Fit (FIT: Pearson and deviance over the pooled cells), Pseudo R-Square (SUMMARY: Cox and Snell, Nagelkerke, McFadden) and Parameter Estimates (PARAMETER: estimate, standard error, Wald, df, significance and CIN interval) without PRINT or when named; Test of Parallel Lines (TPARALLEL: a likelihood ratio test against separate location parameters for each threshold), Cell Information (CELLINFO), Parameter Covariance (COVB), Parameter Correlation (CORB) and Iteration History (HISTORY, every n-th, the first and the last) when named. The -2 log likelihood includes the multinomial constant of the pooled cells; KERNEL leaves it out. A warning counts the empty pooled cells.

SAVE adds EST1_m, EST2_m, … (the first n categories, 25 by default), PRE_m, PCP_m and ACP_m with the smallest free m, or root1, root2, … and the names given: the probability of each category, the most likely category, its probability and the probability of the observed category, for every case with valid factors and covariates. TEST gives Wald tests of combinations of the parameters, in the order of the Parameter Estimates (thresholds, location, scale, redundant ones included): INTERCEPT takes one value per threshold, ALL one per parameter; one TEST uses either ALL in every row or effect names, never both. Each row is tested against its constant (0 by default) on 1 df and the rows together on the rank of their covariance; a coefficient on a redundant parameter multiplies its 0.

Example

PLUM comfort BY seat_row WITH trip_hours /LINK=PROBIT /PRINT=FIT PARAMETER SUMMARY TPARALLEL /SAVE=ESTPROB PREDCAT.

statscraft help PLUM prints the same text in the terminal. All commands

Statscraft 0.61.0, release v0.61.0

QUANTILE REGRESSION

Linear regression of a chosen quantile of the dependent variable, fitted by linear programming.

Syntax

QUANTILE REGRESSION dependent [BY factors] [WITH covariates]
   [/MISSING CLASSMISSING=EXCLUDE | INCLUDE]
   [/CRITERIA [QUANTILE=values [v1 TO v2 BY step]] [IID=TRUE | FALSE]
              [BANDWIDTH=BOFINGER | HALL_SHEATHER] [CILEVEL=95]
              [METHOD=AUTO | SIMPLEX | INTERIOR_POINT] [TOL=1E-12] [CONV=1E-6] [MAXITER=2000]]
   [/MODEL [effects] [REGWGT=var] [INTERCEPT=TRUE | FALSE]]
   [/SAVE [PRED[(name)]] [RESID[(name)]] [CIPREDL[(name)]] [CIPREDU[(name)]]]
   [/PREDICT_EFFECTS NUM_TOP_EFFECTS=3] [/PREDICTION_TABLES effects] [/PREDICTION_LINES effects]
   [/PRINT [PARAMETER] [COVB] [CORB]]
   [/PLOT [MAX_CATEGORIES=10] [PREDICTED_BY_OBSERVED=FALSE | TRUE] [PARAM_EST=50 | ALL]]
   [/OUTFILE [COVB=file] [CORB=file] [FILE_SEPARATE=FALSE | TRUE] [MODEL=file | PARAMETER=file]]
   [/EXTERNAL].

For each quantile p (0.5 unless QUANTILE lists others; a grid v1 TO v2 BY step may join them, a repeated value is fitted once) the coefficients make the weighted sum of p times each positive residual and 1-p times the size of each negative one as small as it can be.

The weight is the case weight, rounded, times REGWGT; a case with a weight below 0.5 or a REGWGT of 0 or less is left out, as is a case missing on any variable (CLASSMISSING=INCLUDE keeps user-missing factor values). MODEL lists effects as in UNIANOVA; without them the model has the intercept and every covariate and factor as a main effect. A parameter that depends on earlier ones is redundant and 0. SIMPLEX walks from vertex to vertex of the linear program to the exact solution; INTERIOR_POINT runs Frisch-Newton steps (TOL for its matrices, CONV for the duality gap, MAXITER steps) and finishes with the simplex from there; AUTO takes the simplex for up to 1000 cases. With IID=TRUE the standard errors come from the spread of the residuals around p over a bandwidth (BOFINGER or HALL_SHEATHER); with FALSE the model is refitted at p plus and minus the bandwidth and each case gets its own density.

t tests and CILEVEL intervals use N minus the number of estimated parameters as df.

Tables: Case Processing Summary, Model Quality (pseudo R squared against the intercept-only fit, mean absolute error), Parameter Estimates (PARAMETER, shown unless PRINT leaves it out), Parameter Covariance (COVB) and Parameter Correlation (CORB). Predicted values over the cells of effects with one or two factors are tables, along one covariate (alone or with factors) line charts, other covariates at their means and other factors averaged: for the effects of PREDICTION_TABLES and PREDICTION_LINES, or else the first NUM_TOP_EFFECTS such effects of the model. PLOT PREDICTED_BY_OBSERVED adds a scatter of each case per quantile, PARAM_EST a chart of each of the first n estimated parameters across the quantiles (with two or more).

SAVE adds the predicted value, residual and interval bounds (named PRED, RESID, CIPREDL and CIPREDU unless a name is given; with several quantiles the name gets _ and the quantile’s digits, as in PRED_25). OUTFILE COVB or CORB writes RowType_, VarName_ and P1, P2, … with rows EST, SE, SIG, DF and then COV or CORR to a data file or declared dataset (a Quantile column joins several quantiles; FILE_SEPARATE=TRUE writes one file each, the quantile’s digits added to the name). MODEL or PARAMETER writes the estimates (MODEL with their covariances) to a JSON file of Statscraft’s own, one per quantile. EXTERNAL changes nothing.

Example

QUANTILE REGRESSION rent BY district WITH floor_area /CRITERIA QUANTILE=0.25 0.5 0.75 IID=FALSE /PRINT PARAMETER COVB /SAVE PRED(fit) RESID.

statscraft help QUANTILE REGRESSION prints the same text in the terminal. All commands

Statscraft 0.61.0, release v0.61.0

PLS

Partial least squares regression of one or more dependent variables on many, possibly collinear, predictors.

Syntax

PLS dependent [MLEVEL=N | O | S] [REFERENCE=FIRST | LAST | value] [dependent ...]
   [BY factors] [WITH covariates]
   [/ID VARIABLE=var] [/MODEL effects]
   [/OUTDATASET [CASES=dataset] [LATENTFACTORS=dataset] [PREDICTORS=dataset]]
   [/CRITERIA LATENTFACTORS=5].

Each subcommand and keyword at most once, written in full, with its equals sign. A dependent is scale or categorical: MLEVEL after it, else its measurement level, else scale for a number and categorical for a string (N and O both mean categorical). ALL MLEVEL=… or ALL REFERENCE=… sets every dependent that has no setting of its own. A categorical dependent becomes one 0/1 column per category except the reference one (REFERENCE: FIRST, LAST by default, or a value that occurs). Factors follow BY, covariates WITH; a factor gives a 0/1 column for every level, an interaction one column per combination of levels that occurs (times the covariates in it). MODEL lists main effects and interactions (a*b or a BY b), the main effects of all predictors by default; nested terms are not taken.

Every column is centered and divided by its standard deviation. Cases missing on any variable (user-missing too) are left out; the weight is rounded and a case below 1 is left out. NIPALS extracts up to LATENTFACTORS factors, no more than the predictor columns or the cases less one. Tables: Proportion of Variance Explained (X and Y, cumulative, R-square and adjusted R-square), Parameters (constant and coefficient of every predictor column in the original units), Variable Importance in the Projection (cumulative by factor), Weights and Loadings. OUTDATASET writes named datasets: CASES (ID or case number, predicted values and residuals, the distance to the X model, the X and Y scores) for every case with valid predictors, LATENTFACTORS (loadings and weights of each variable) and PREDICTORS (coefficients and VIP of each predictor column). Under SPLIT FILE every group is fitted and the datasets hold the groups one after the other, with the split variables in front (the case number is that of the whole file). No plots.

Example

PLS yield MLEVEL=S quality MLEVEL=N REFERENCE=FIRST BY plot WITH rain sun soil_ph /CRITERIA LATENTFACTORS=3 /OUTDATASET CASES=plsCases.

statscraft help PLS prints the same text in the terminal. All commands

Statscraft 0.61.0, release v0.61.0

GENLIN

Generalized linear models: normal, binomial, Poisson, gamma, inverse Gaussian, negative binomial and ordinal responses.

Syntax

GENLIN dependent [(REFERENCE=LAST | FIRST | value)] [(ORDER=ASCENDING | DESCENDING | DATA)]
   | events OF trials-variable | n
   [BY factors [(ORDER=ASCENDING | DESCENDING | DATA)]] [WITH covariates]
   [/MODEL [effects] [INTERCEPT=YES | NO] [OFFSET=variable | value] [SCALEWEIGHT=variable]
           [DISTRIBUTION=NORMAL | BINOMIAL | GAMMA | IGAUSS | POISSON | NEGBIN[(k | MLE)] | TWEEDIE(q) | MULTINOMIAL]
           [LINK=IDENTITY | LOG | LOGIT | PROBIT | CLOGLOG | NLOGLOG | LOGC | NEGBIN | POWER(a) |
                 ODDSPOWER(a) | CUMLOGIT | CUMPROBIT | CUMCLOGLOG | CUMNLOGLOG | CUMCAUCHIT]]
   [/CRITERIA [ANALYSISTYPE=3 | 1 | ALL [(WALD | LR)]] [CHECKSEP=20] [CILEVEL=95] [CITYPE=WALD | PROFILE[(1E-4)]] [INITIAL=numbers | 'file' | dataset]
              [COVB=MODEL | ROBUST] [HCONVERGE=0] [LCONVERGE=0] [PCONVERGE=1E-6] (each [(ABSOLUTE | RELATIVE)])
              [LIKELIHOOD=FULL | KERNEL] [MAXITERATIONS=100] [MAXSTEPHALVING=5]
              [METHOD=FISHER[(n)] | NEWTON] [SCALE=MLE | DEVIANCE | PEARSON | value] [SINGULAR=1E-12]]
   [/EMMEANS [TABLES=factor[*factor...]] [CONTROL=covariate(value | MEAN) ...]
             [SCALE=ORIGINAL | TRANSFORMED] [COMPARE=factor[*factor...]]
             [CONTRAST=PAIRWISE | DEVIATION[(value)] | DIFFERENCE | HELMERT | POLYNOMIAL[(metric)] |
                       REPEATED | SIMPLE[(value)]]
             [PADJUST=LSD | BONFERRONI | SEQBONFERRONI | SIDAK | SEQSIDAK]] ...
   [/REPEATED SUBJECT=variable[*variable...] [WITHINSUBJECT=variable[*variable...]] [SORT=YES | NO]
             [CORRTYPE=INDEPENDENT | AR(1) | EXCHANGEABLE | MDEPENDENT(m) | UNSTRUCTURED | FIXED(list)]
             [ADJUSTCORR=YES | NO] [COVB=ROBUST | MODEL] [HCONVERGE=0] [MAXITERATIONS=100]
             [PCONVERGE=1E-6[(ABSOLUTE | RELATIVE)]] [UPDATECORR=1]]
   [/MISSING CLASSMISSING=EXCLUDE | INCLUDE]
   [/PRINT [CPS] [DESCRIPTIVES] [MODELINFO] [FIT] [SUMMARY] [SOLUTION[(EXPONENTIATED)]] [COVB] [CORB]
           [GEF] [HISTORY[(n)]] [LAGRANGE] [LMATRIX] [WORKINGCORR] | NONE]
   [/SAVE [XBPRED] [XBSTDERROR] [MEANPRED] [CIMEANPREDL] [CIMEANPREDU] [PREDVAL] [LEVERAGE] [RESID]
          [PEARSONRESID] [DEVIANCERESID] [STDPEARSONRESID] [STDDEVIANCERESID] [LIKELIHOODRESID] [COOK]
          (each [(name)]; the first five [(root[:n])])]
   [/OUTFILE COVB='file' | dataset | CORB='file' | dataset].

The command fits a generalized linear model with factors after BY and covariates after WITH. The response is one dependent variable or events OF trials, where trials is a variable or a whole number of 1 or more. Covariates, the offset and the scale weight are numeric; factors and a categorical dependent may be strings. TO is not accepted: name every variable. Keywords are written in full, and every subcommand but EMMEANS appears at most once. Effects are written as in UNIANOVA.

Without DISTRIBUTION, events/trials is BINOMIAL (the only one it allows) and any other response NORMAL. The default LINK is IDENTITY for NORMAL, LOGIT for BINOMIAL, POWER(-1) for GAMMA, POWER(-2) for IGAUSS, LOG for POISSON and NEGBIN, POWER(1-q) for TWEEDIE, CUMLOGIT for MULTINOMIAL. MULTINOMIAL (an ordinal response) allows only the CUM links, BINOMIAL every other link but NEGBIN, NEGBIN also its own link unless k is 0, and the rest IDENTITY, LOG or POWER; another pair is an error. NEGBIN alone fixes k at 1, NEGBIN(MLE) estimates it. TWEEDIE(q), q above 1 and below 2, is the compound Poisson-gamma distribution with the variance function mu^q (zero or positive responses, the scale as for GAMMA).

A binary dependent must have two values; the model gives the probability of the one that is not the REFERENCE (LAST by default, in the ORDER given). A factor has one column per level, and the column of its last level is redundant and shown as 0. The ordinal model has thresholds instead of an intercept.

A case is left out when its rounded weight is below 1, a variable is missing, the scale weight is not positive, or the response is out of range: not above 0 for GAMMA and IGAUSS, below 0 for TWEEDIE, not a whole number of 0 or more for POISSON and NEGBIN, or events above trials. CLASSMISSING=INCLUDE keeps user-missing factor values.

Without PRINT the output is MODELINFO, CPS, DESCRIPTIVES, FIT, SUMMARY and SOLUTION; a PRINT list replaces this set, and NONE stands alone. FIT gives the deviance, Pearson chi-square, log likelihood (full or KERNEL) and information criteria. SUMMARY gives the Omnibus Test against the intercept-only model and the Tests of Model Effects: Type III by default (ANALYSISTYPE=1, 3 or ALL), Wald unless (LR) is given. SOLUTION gives the Parameter Estimates with Wald intervals; (EXPONENTIATED) adds Exp(B). COVB and CORB add the matrices of the estimates.

METHOD=FISHER(n) uses Fisher scoring for the first n iterations and Newton-Raphson after: FISHER(1) is the default, FISHER alone scores throughout. A step is halved, at most MAXSTEPHALVING times, while the log likelihood falls. At least one of HCONVERGE, LCONVERGE and PCONVERGE must be above 0. SCALE=MLE estimates the scale; it is the default for NORMAL, GAMMA, IGAUSS and TWEEDIE and an error for the others, which fix it at 1. DEVIANCE or PEARSON set it to that chi-square over its df, then divide the likelihood ratio statistics by it and add an F test. A number fixes the scale. COVB=ROBUST gives the sandwich covariance.

EMMEANS gives the estimated marginal means of the TABLES cells, covariates at their means or the CONTROL values, on the response scale (ORIGINAL) or the linear predictor (TRANSFORMED). COMPARE takes factors from TABLES and adds pairwise comparisons, or the CONTRAST given, adjusted by PADJUST (LSD by default), with an overall Wald test. CONTRAST needs COMPARE, and crossed COMPARE factors allow only PAIRWISE.

SAVE names each variable as given or after its keyword (XBPredicted, MeanPredicted, Residual and so on, with the suffix _1 when taken). For a multinomial response the first five keywords give one variable per category, at most n (25 by default).

REPEATED fits generalized estimating equations for cases correlated within a subject: one combination of the SUBJECT values (required). WITHINSUBJECT values order a subject’s cases, and a value a subject lacks is a missing measurement; without it the file order is kept. SORT=NO takes each run of equal SUBJECT values as a subject and ignores WITHINSUBJECT. A frequency weight must be equal within a subject. CORRTYPE is INDEPENDENT by default; the other estimated structures use the Pearson residuals, and ADJUSTCORR=YES (the default) subtracts the number of parameters in each denominator. FIXED lists the correlations below the diagonal row by row, each from 0 to 1. UPDATECORR=n re-estimates the matrix every n iterations (0 never), at most MAXITERATIONS.

With REPEATED, its own COVB applies (ROBUST by default) and the CRITERIA COVB is ignored. SCALE=MLE becomes the Pearson estimate; another scale and an estimated k keep the value of the model without REPEATED. FIT shows QIC and QICC, SUMMARY only the Wald tests of the effects, CPS adds the Correlated Data Summary, and WORKINGCORR (used only here) the working correlation matrix. (LR) gives generalized score chi-squares. SAVE gives no leverage, deviance-based or standardized residuals, or Cook’s distance.

With the ordinal MULTINOMIAL distribution REPEATED takes every CORRTYPE but FIXED. INDEPENDENT gives the estimates of the model without REPEATED, the covariance is the inverse of the expected information (COVB=MODEL) or the sandwich over the subjects (ROBUST). EXCHANGEABLE, AR(1), MDEPENDENT(m) and UNSTRUCTURED estimate a matrix of association between the residuals of each pair of the first categories at two measurements, from the Pearson-like residuals, and solve the estimating equations by iteration; a subject whose working matrix is not positive definite is moved toward the identity and a warning counts them. WORKINGCORR shows those association matrices. The Wald tests, not the omnibus test, goodness of fit or (LR), are given.

LAGRANGE tests a fixed scale (NORMAL, GAMMA or IGAUSS) or a fixed NEGBIN k with 1 df; for k = 0 it gives the z of the dispersion regression. HISTORY(n) lists every n-th iteration and the last, then the final gradient and Hessian. GEF shows the general estimable function and LMATRIX the L’ matrix of each test and marginal mean, neither for the ordinal model.

INITIAL gives numbers for all parameters in table order, redundant ones included; another count is an error. A file or dataset gives them in its first record with RowType_ EST (the variables after VarName_, in order, the scale parameter and the negative binomial parameter after the others and not used; a file of several SPLIT FILE groups is read group by group). INITIAL is ignored with a warning for NORMAL with IDENTITY and for the ordinal model. OUTFILE writes such a file, a .sav file or a dataset made with DATASET DECLARE: RowType_, VarName_ and a column P1, P2, … for every parameter in table order (a redundant one blank), the scale parameter and, for NEGBIN, k. COVB gives a COV record per estimated parameter with its covariances, CORB a CORR record with its correlations; then come the records EST (the estimates, the redundant ones 0), SE, SIG (the Wald significances) and DF (1 for each estimated parameter). MODEL and PARAMETER (XML files) are not written. CITYPE=PROFILE replaces the Wald intervals of the parameters, Exp(B) and an estimated scale or k with profile likelihood intervals, refitting the other parameters (a DEVIANCE or PEARSON scale is held); its tolerance sets how closely the limits are solved, and a limit never reached is left empty. The ordinal model and REPEATED keep Wald intervals with a warning.

Example

GENLIN visits BY clinic WITH age /MODEL clinic age DISTRIBUTION=NEGBIN(MLE) LINK=LOG OFFSET=logdays /PRINT FIT SUMMARY SOLUTION(EXPONENTIATED) /EMMEANS TABLES=clinic COMPARE=clinic.

statscraft help GENLIN prints the same text in the terminal. All commands

Statscraft 0.61.0, release v0.61.0

UNIANOVA

General linear model of one dependent variable: factorial ANOVA, ANCOVA and regression.

Syntax

UNIANOVA dependent [BY factors] [WITH covariates]
   [/DESIGN=effects] [/METHOD=SSTYPE(1 | 2 | 3 | 4)] [/INTERCEPT=INCLUDE | EXCLUDE]
   [/MISSING=EXCLUDE | INCLUDE] [/CRITERIA=[EPS(1E-8)] [ALPHA(0.05)]] [/REGWGT=var]
   [/PRINT=[DESCRIPTIVE] [HOMOGENEITY] [PARAMETER] [ETASQ] [OPOWER] [LOF] [GEF] [MBP] [BP] [F] [WHITE]
          [TEST(LMATRIX | ESTIMABLE)]]
   [/EMMEANS=TABLES(OVERALL | factor[*factor...]) [WITH(covariate=value | MEAN ...)]
             [COMPARE[(factor)] [ADJ(LSD | BONFERRONI | SIDAK)]]] ...
   [/POSTHOC=factor ... (tests) [VS effect]] ...
   [/CONTRAST(factor)=DEVIATION[(ref)] | SIMPLE[(ref)] | DIFFERENCE | HELMERT | REPEATED |
                      POLYNOMIAL[(metric)] | SPECIAL(matrix)] ...
   [/LMATRIX=['label'] effect coefficients ... [; ...] | ALL coefficients] ... [/KMATRIX=values [; ...]]
   [/TEST=effect VS coefficient*effect +/- ... [DF(df)] | value DF(df)] ...
   [/ROBUST[=HC0 | HC1 | HC2 | HC3 | HC4]] [/RANDOM=factors]
   [/MBPDESIGN[=effects]] [/BPDESIGN[=effects]] [/FDESIGN[=effects]]
   [/SAVE=tempvar[(name)] ...]
   [/OUTFILE=[COVB('file' | dataset)] [CORB('file' | dataset)] [HCCOVB('file' | dataset)] [EFFECT('file' | dataset)] [DESIGN('file' | dataset)]]
   [/PLOT=[SPREADLEVEL] [RESIDUALS] [PROFILE(factor[*factor[*factor]] ...) [WITH(covariate=value | MEAN ...)]
          [TYPE=LINE | BAR] [MEANREFERENCE=NO | YES] [ERRORBAR=NO | CI | SE[(2)]] [YAXIS=AUTO | 0]]] ...

The command fits a general linear model to one dependent variable: analysis of variance with factors after BY, analysis of covariance with covariates after WITH, or regression. Without DESIGN the model is the intercept, the covariates and the full factorial of the factors. Effects on DESIGN: INTERCEPT, a factor or covariate, a*b or a BY b (interaction), a(b) or a WITHIN b (nesting, also a(b(c))), x*x and x*a. Sums of squares are Type III unless METHOD says otherwise (Type I is sequential). A case missing on any variable is left out (MISSING=INCLUDE keeps user-missing values), and the weight is rounded to a whole number. A design column that adds nothing (CRITERIA EPS) is redundant and its parameter is 0. For several dependent variables or repeated measures use GLM.

The main table is Tests of Between-Subjects Effects; ETASQ adds partial eta squared and OPOWER the noncentrality and observed power. DESCRIPTIVE gives cell means, PARAMETER the parameter estimates, LOF a lack of fit test. HOMOGENEITY gives Levene’s test on the absolute residuals by cell; for a full factorial without covariates also its versions based on the median, the median with adjusted df and the trimmed mean.

EMMEANS gives estimated marginal means with the cells weighted equally and the covariates at their means or the WITH values; COMPARE adds pairwise comparisons and univariate tests, adjusted by ADJ. POSTHOC runs the post hoc tests of ONEWAY on the observed means with the model’s error: LSD BONFERRONI SIDAK TUKEY SCHEFFE GH T2 SNK BTUKEY DUNCAN GT2 GABRIEL FREGW QREGW T3 C DUNNETT DUNNETTL DUNNETTR. T2, T3, GH and C need a model with one factor. VS names another effect of the design (not the intercept, nor a main effect on the same POSTHOC) as the error term of the pairwise and subset tests.

CONTRAST(factor) tests the factor’s levels by a contrast type (DEVIATION by default); SPECIAL(matrix) takes a k x k matrix for k levels, column by column, the first column the constant (the k - 1 contrast columns alone also work), without fractions. LMATRIX gives custom contrasts of the parameters, rows ending with ‘;’, and KMATRIX their hypothesized values (0 by default). Each gives Contrast Results and Test Results. TEST(LMATRIX) shows the L matrix of every effect, LMATRIX and CONTRAST; GEF gives the general form of the estimable functions.

TEST=effect VS … tests an effect against an error term: a combination of the mean squares of other effects (coefficients may be fractions) with Satterthwaite’s degrees of freedom unless DF(df) gives them, or a value with its DF(df). RANDOM=factors makes those factors random, with every effect that holds one: each effect is tested against the combination of mean squares that matches its expected mean square (Satterthwaite’s df), and an Expected Mean Squares table is added; ETASQ and OPOWER then measure each effect against its error term. The other tables keep the fixed-effects error, with a warning.

ROBUST (HC3 when no type is named) adds Robust Parameter Estimates and Robust Tests of Between-Subjects Effects with a heteroskedasticity-consistent covariance, and robust results for CONTRAST and LMATRIX. PRINT=MBP, BP, F and WHITE test for heteroskedasticity by regressing the squared residuals on the fitted values and their squares, or on the effects of MBPDESIGN, BPDESIGN or FDESIGN (bare: the effects of DESIGN); WHITE uses every column, square and cross product of the design.

SAVE adds variables to the data: PRED WPRED RESID WRESID DRESID ZRESID SRESID SEPRED COOK LEVER, named PRE_1, RES_1 and so on unless a name is given. OUTFILE writes files for one dependent variable without RANDOM, each to a .sav file or a dataset made with DATASET DECLARE (a different one for each keyword; under SPLIT FILE the split variables come first and the groups follow one another): COVB the parameter covariance matrix and CORB their correlation matrix, as RowType_ (COV or CORR), VarName_ and a column P1, P2, … for every parameter in the order of the Parameter Estimates (a redundant one blank), with a record per estimated parameter and then the records EST (the estimates, a redundant one 0), SE, DF (the error degrees of freedom) and SIG (the significance of t), named by the dependent variable; HCCOVB the covariance matrix of the robust estimator of ROBUST (needed) in the layout of COVB but with its diagonal terms only, and the robust standard errors and the significances they give; EFFECT the Tests of Between-Subjects Effects, a record per row of that table with SOURCE_ and SS, DF, MS, F and SIG (and ETASQ, NONCENT and POWER when PRINT asks for them), a value the table leaves empty being missing; DESIGN the design matrix of the cases used, one variable DES_1, DES_2, … for each parameter. PLOT gives chart data. PROFILE draws the estimated marginal means over the levels of the first factor, one line per level of a second factor and one chart per level of a third (TYPE=BAR for bars); MEANREFERENCE adds the grand mean, ERRORBAR=CI the confidence intervals at 1 minus ALPHA, and SE(n) n standard errors (2 by default). SPREADLEVEL plots each cell’s mean against its standard deviation and variance; RESIDUALS plots the observed, predicted and standardized residual values.

Example

UNIANOVA score BY method school WITH pretest /PRINT=DESCRIPTIVE ETASQ PARAMETER /EMMEANS=TABLES(method) COMPARE ADJ(BONFERRONI) /DESIGN=pretest method school method*school.

statscraft help UNIANOVA prints the same text in the terminal. All commands

Statscraft 0.61.0, release v0.61.0

GLM

General linear model: one dependent variable as in UNIANOVA, several (multivariate analysis of variance and covariance), or repeated measures with WSFACTOR.

Syntax

GLM dependents [BY factors] [WITH covariates]
   [/WSFACTOR=name levels [POLYNOMIAL | contrast] ...] [/WSDESIGN=effects] [/MEASURE=names]
   [/MMATRIX=['label'] dependent value ... | ALL values [; ...]] [/KMATRIX=values [; ...]]
   [/PRINT=... [RSSCP] [TEST([SSCP] [LMATRIX | ESTIMABLE] [MMATRIX | TRANSFORM])]]
   [/every other subcommand of UNIANOVA]

The command is the general linear model of UNIANOVA extended to several dependent variables and to repeated measures. With one dependent and no WSFACTOR it is UNIANOVA: the same subcommands, defaults, rules and tables, all described under UNIANOVA. This page gives only what is added.

Several dependents without WSFACTOR make the multivariate model, a multivariate analysis of variance or covariance. Every effect gets Multivariate Tests (Pillai’s trace, Wilks’ lambda, Hotelling’s trace and Roy’s largest root, each with F, df and Sig.; with ETASQ and OPOWER also partial eta squared, noncentrality and power), then the univariate tables with a row per dependent. HOMOGENEITY adds Box’s M test of equal covariance matrices to Levene’s test of each dependent. RSSCP gives the residual SSCP, covariance and correlation matrices and Bartlett’s test of sphericity; TEST(SSCP) gives the SSCP of each effect and of the error. EMMEANS, POSTHOC, PLOT and SAVE work on each dependent in turn; SAVE PRED(p1 p2) names the new variable of each dependent in their order, one left without a name gets the default PRE_n.

MMATRIX transforms the dependents for a custom test L B M = K: each column ends with ‘;’ and is named by its label or T1, T2, … (the identity by default). L comes from LMATRIX (the intercept’s test when only MMATRIX or KMATRIX is given) and K from KMATRIX (rows end with ‘;’, zero by default). CONTRAST always uses the identity. Each test gives Contrast Results (K Matrix), Multivariate Test Results and Univariate Test Results; TEST(MMATRIX) shows M.

WSFACTOR makes the dependents the levels of within-subjects factors, for example GLM t1 t2 t3 t4 t5 t6 /WSFACTOR=time 3 task 2: the first factor’s levels change slowest, and the number of dependents must be the product of the levels (times the number of measures). The factor’s contrast (POLYNOMIAL by default) gives the within-subjects contrasts. WSDESIGN lists the within-subjects effects (by default their full factorial). The tables are Multivariate Tests, Mauchly’s Test of Sphericity, Tests of Within-Subjects Effects (sphericity assumed, Greenhouse-Geisser, Huynh-Feldt and lower bound), Tests of Within-Subjects Contrasts, and Tests of Between-Subjects Effects on the average of the levels. PROFILE may plot within-subjects factors too; SPREADLEVEL and RESIDUALS are left out with a warning.

MEASURE=names makes a doubly multivariate model: the dependents are the cells of the within-subjects design for the first measure, then for the second, and so on. Each measure gets its own sphericity, within-subjects, contrast and between-subjects tests, and the multivariate tests take the measures together. TEST, ROBUST and RANDOM are for one dependent without WSFACTOR; ROBUST is ignored with a warning otherwise. RANDOM runs the whole univariate analysis of each dependent, so the univariate subcommands (TEST and ROBUST too) then apply to each one.

Example

GLM t1 t2 t3 BY group /WSFACTOR=time 3 POLYNOMIAL /WSDESIGN=time /DESIGN=group.

statscraft help GLM prints the same text in the terminal. All commands

Statscraft 0.61.0, release v0.61.0

MANOVA

Analysis of variance and covariance for one or several dependents, with nested and pooled terms, partitions and chosen error terms.

Syntax

MANOVA dependents [BY factors (min,max) [factors (min,max) ...]] [WITH covariates] [(covariates)]
   [/WSFACTORS=name [name ...] (levels) ...] [/WSDESIGN=term [term ...]] [/MEASURE=names]
   [/TRANSFORM[(varlist [/varlist ...])]=[ORTHONORM] [CONTRAST | BASIS] type] [/RENAME=name | * ...]
   [/ERROR=WITHIN | RESIDUAL | WR | n] [/METHOD=[UNIQUE | SEQUENTIAL] [CONSTANT | NOCONSTANT] [QR | CHOLESKY]]
   [/CONTRAST(factor)=DEVIATION[(ref)] | SIMPLE[(ref)] | DIFFERENCE | HELMERT | REPEATED |
                      POLYNOMIAL[(metric)] | SPECIAL(matrix)] ... [/PARTITION(factor)[=(n, m*k ...)]] ...
   [/PRINT | NOPRINT=[CELLINFO[(MEANS SSCP COV COR ALL)]] [HOMOGENEITY[(BARTLETT COCHRAN BOXM ALL)]]
         [PARAMETERS[(ESTIM NEGSUM ORTHO COR EFSIZE ALL)]] [DESIGN[(OVERALL ONEWAY DECOMP COLLINEARITY)]] [TRANSFORM]
         [SIGNIF(MULTIV UNIV EIGEN DIMENR HYPOTH STEPDOWN BRIEF SINGLEDF AVERF AVONLY GG HF EFSIZE)]
         [ERROR[(SSCP COV COR STDDEV)]]]
   [/OMEANS=[VARIABLES(varlist)] TABLES(factor [BY factor] | CONSTANT, ...)]
   [/PMEANS[=[VARIABLES(dependents)] [TABLES(factor [BY factor] | CONSTANT, ...)] [PLOT]]]
   [/CINTERVAL=[INDIVIDUAL | JOINT][(level)]
              [UNIVARIATE(SCHEFFE | BONFER) | MULTIVARIATE(ROY | PILLAI | WILKS | HOTELLING | BONFER)]]
   [/POWER[=[F(alpha)] [T(alpha)] [APPROXIMATE | EXACT]]] [/RESIDUALS[=CASEWISE] [PLOT]]
   [/PLOT=[BOXPLOTS] [CELLPLOTS] [NORMAL] [ZCORR]]
   [/PCOMPS=[COR] [COV] [ROTATE[(VARIMAX | EQUAMAX | QUARTIMAX | NOROTATE)]] [NCOMP(n)]
            [MINEIGEN(value)] [ALL]]
   [/DISCRIM[=[RAW] [STAN] [ESTIM] [COR] [ROTATE[(VARIMAX | EQUAMAX | QUARTIMAX)]] [ALL]
             [ALPHA(value)]]]
   [/ANALYSIS[(CONDITIONAL | UNCONDITIONAL)]=dependents [WITH covariates]
      | (dependents [WITH covariates] [/ ...]) [WITH covariates]]
   [/MISSING=[LISTWISE] [EXCLUDE | INCLUDE]] [/MATRIX=IN(file | dataset | *) OUT(file | dataset | *)]
   [/DESIGN=term [term ...]] [/DESIGN ...].

The command fits a linear model to one or more dependents, with factors after BY and covariates after WITH. A range (min,max) applies to every factor before it, with one level per whole number; values are cut to whole numbers. Cases outside a range or missing on any listed variable are left out (MISSING=INCLUDE keeps user-missing values). Weights are used as they are. Each DESIGN runs one analysis with the settings given before it, which carry over. Without a final DESIGN, a full factorial design is added. With one dependent the output is Tests of Significance (each error term with its terms, the covariate regression, (Model), (Total), R-squared); with several, Multivariate Tests of Significance (Pillai, Wilks, Hotelling, Roy) and Univariate F-tests.

Design terms, separated by spaces or commas: an item is a factor, a continuous variable or POOL(varlist); items are crossed with BY and nested with WITHIN (or W). A factor written a(n) keeps partition n of its df, one df each or as PARTITION(a)=(n, m*k) groups them. After WITHIN, b(n) means level n of b alone; a term that starts with MWITHIN b(n) is the constant at that level. A plus sign pools effects into one test, ‘= n’ makes the term error term n (1 to 10), VS (or AGAINST, VERSUS) names its error, and MUPLUS joins the constant to the next term. A continuous variable on DESIGN must be a dependent or covariate that ANALYSIS leaves out. The constant is fitted first but shown only when written as CONSTANT or without factors; METHOD=NOCONSTANT drops it unless written.

ERROR picks the error term: WITHIN (W), the pooled within-cell matrix; RESIDUAL (R), what the design leaves out of the cell model; WR (RW), both; or a numbered term. The default is WITHIN, RESIDUAL when no cell holds two cases, and WR when DESIGN has a continuous variable. METHOD=UNIQUE (the default) adjusts each term for all others, SEQUENTIAL for the terms before it. CONTRAST(factor) sets the coding, DEVIATION by default (last level left out). Covariates are removed from every test within the error term (one df each) and tested as a regression.

TRANSFORM replaces the continuous variables (all, or each list in turn) by T1, T2 and so on, from a contrast type whose first row is the mean (SPECIAL takes a square matrix); BASIS uses its transposed inverse, ORTHONORM makes the rows orthonormal. RENAME names every continuous variable in order (‘*’ keeps a name); later subcommands use the new names, OMEANS the originals. ANALYSIS picks the dependents and covariates. Groups in parentheses, separated by slashes, are separate analyses; CONDITIONAL makes earlier groups covariates of later ones, and covariates after the closing parenthesis go to every group.

Repeated measures: WSFACTORS, the first subcommand, reads the dependents as the cells of the within-subjects factors (2 or more levels each), the last changing fastest, once per measure named on MEASURE. Contrasts are POLYNOMIAL unless CONTRAST says otherwise; between-subjects tests use the cell mean. WSDESIGN lists within-subjects terms (all main effects and interactions by default), each crossed with the DESIGN terms. Covariates outside parentheses come one per cell; those in parentheses are constant. An effect with several df gets Mauchly’s test with Greenhouse-Geisser, Huynh-Feldt and lower-bound epsilons, and averaged F tests (AVERF, the default). GG and HF add tests with epsilon-scaled df; AVONLY drops the multivariate tests. SIGNIF(UNIV) is off by default here.

PRINT adds tables, NOPRINT removes them; a keyword alone means its defaults. SIGNIF adds EIGEN (eigenvalues, canonical correlations), DIMENR (dimension reduction), HYPOTH (hypothesis SSCP), STEPDOWN (stepdown F), SINGLEDF (a test per df), EFSIZE (partial eta squared, also under PARAMETERS) or BRIEF (Wilks only); MULTIV and UNIV are on by default. PARAMETERS gives estimates with standard error, t, Sig. and interval (ESTIM, default), NEGSUM (minus their sum), ORTHO (orthogonal estimates) or COR (their correlations). ERROR prints error matrices (COV, COR, STDDEV by default, or SSCP), TRANSFORM the transformation matrix, DESIGN the design matrix (OVERALL, default), ONEWAY bases, DECOMP the upper triangular factor R of the weighted design (R’R = X’WX, positive diagonal, a zero row for a redundant column) or COLLINEARITY the singular values of the design with its columns scaled to unit length, their condition indexes and the share of each parameter’s variance that goes with each singular value. CELLINFO gives cell MEANS (default), SSCP, COV or COR; HOMOGENEITY gives BARTLETT, COCHRAN and BOXM (all by default).

OMEANS gives weighted and unweighted means of the VARIABLES over the factors on TABLES; alone it gives cell means. PMEANS gives observed, adjusted and estimated cell means with residuals, and with TABLES adjusted means over the other factors. RESIDUALS lists each case’s predictions and residuals. CINTERVAL sets estimate intervals: INDIVIDUAL at the level given (0.95 by default), or JOINT over a term’s parameters by SCHEFFE or BONFER. MULTIVARIATE widens them to cover all dependents (ignored with one). POWER adds noncentrality and observed power to F tests (alpha F(.05)) and t tests (T(.05)); multivariate tests use APPROXIMATE power, or EXACT power only for one-df effects.

With several dependents, PCOMPS gives principal components of the error matrix as COR or COV, for eigenvalues of at least MINEIGEN (0). ROTATE turns the first NCOMP (all) by VARIMAX unless named, until NOROTATE. ALL means COR, COV and ROTATE. DISCRIM gives discriminant functions of each multivariate effect and the covariates, kept while their dimension reduction Sig. is at most ALPHA (0.25). It shows RAW and STAN coefficients, ESTIM (estimates times coefficients) and COR (dependent-function correlations), all four by default; ALL adds ROTATE.

MATRIX=OUT writes N (total and per cell), each cell’s MEAN with its factor values between ROWTYPE_ and VARNAME_, and the within-cell STDDEV and CORR. MATRIX=IN analyzes such a file, or a CORRELATIONS file as one cell; CELLINFO, HOMOGENEITY, RESIDUALS and PLOT are refused then. PLOT draws, once per command, BOXPLOTS (the default), CELLPLOTS (cell means against spreads), NORMAL (normal and detrended plots) and ZCORR (half-normal plot of within-cell correlations). PMEANS PLOT draws adjusted predicted cell means; RESIDUALS PLOT draws standardized residuals against observed, predicted and case number, with normal plots. RESIDUALS=PLOT alone skips the listing.

Example

MANOVA score1 score2 BY method(1,3) school(1,2) WITH pretest /PRINT=SIGNIF(EIGEN) /DESIGN.
MANOVA t1 t2 t3 BY method(1,3) /WSFACTORS=trial(3) /PRINT=SIGNIF(GG HF) /DESIGN.

statscraft help MANOVA prints the same text in the terminal. All commands

Statscraft 0.61.0, release v0.61.0

MIXED

Linear mixed model: fixed effects with random effects of subjects and correlated repeated measures.

Syntax

MIXED dependent [BY factors] [WITH covariates]
   [/FIXED=[effects] [| [NOINT] [SSTYPE(3 | 1)]]] [/METHOD=REML | ML] [/MISSING=EXCLUDE | INCLUDE]
   [/RANDOM=effects [| [SUBJECT(var[*var...])] [COVTYPE(type)] [SOLUTION]]] ...
   [/REPEATED=var[*var...] | SUBJECT(var[*var...]) [COVTYPE(type)]] [/REGWGT=var]
   [/CRITERIA=[CIN(95)] [MXITER(100)] [MXSTEP(10)] [SCORING(1)] [SINGULAR(1E-12)]
             [PCONVERGE(1E-6[, ABSOLUTE | RELATIVE])] [LCONVERGE(0[, ...])] [HCONVERGE(0[, ...])]
             [DFMETHOD(SATTERTHWAITE | RESIDUAL | KENWARDROGER)]]
   [/PRINT=[SOLUTION] [TESTCOV] [G] [R] [COVB] [CORB] [CPS] [DESCRIPTIVES] [HISTORY[(n)]] [LMATRIX]]
   [/SAVE=tempvar[(name)] ...]
   [/EMMEANS=TABLES(OVERALL | factor[*factor...]) [WITH(covariate=value | MEAN ...)]
             [COMPARE[(factor)] [REFCAT(value | FIRST | LAST)] [ADJ(LSD | BONFERRONI | SIDAK)]]] ...
   [/TEST[(constants)]=['label'] effect values ... [| effect values ...] [DIVISOR=n]; ...
          | ALL values ... [| values ...] ...] ...

The command fits a linear mixed model to one dependent. The fixed part is the intercept (unless NOINT) plus the FIXED effects, written as INTERCEPT (first), a factor or covariate, a*b (a BY b) or a(b) (a WITHIN b). RANDOM, EMMEANS and TEST may repeat; for other subcommands the last one wins. A case missing on any variable named is left out (INCLUDE keeps user-missing values). Weights are rounded to frequency counts; REPEATED allows only a weight of 1. REGWGT divides the residual covariance of a case by its value.

Each RANDOM adds one covariance block per subject, the same for all; subjects and RANDOM subcommands are independent, and INTERCEPT is never implied there. Without SUBJECT the whole file is one subject. REPEATED orders the levels of its variables and gives each SUBJECT (required) a residual block; without it the residuals share one variance. A RANDOM subject variable must also be a REPEATED subject variable. COVTYPE is VC on RANDOM (one variance per effect) and DIAG on REPEATED (one variance per level; VC there means DIAG). Other types: ID (one variance), UN (unstructured), CS (a common covariance plus a diagonal offset), CSR (one variance, one correlation), AR1 (first-order autoregressive), ARMA11, TP (Toeplitz), AD1 (antedependence), UNR (a correlation per pair), HF (Huynh-Feldt), FA1 (one factor plus a diagonal offset). CSH, ARH1, TPH and FAH1 are CSR, AR1, TP and FA1 with a variance (FAH1: an offset) per level.

METHOD=REML (the default) maximizes the restricted likelihood, ML the full one. The fit takes up to MXITER Newton steps (the first SCORING with the expected Hessian), halving a step up to MXSTEP times. It stops when every parameter changes less than PCONVERGE, or by LCONVERGE or HCONVERGE when set (ABSOLUTE by default, or RELATIVE). CIN sets the interval level. DFMETHOD picks the df: Satterthwaite (the default), RESIDUAL (cases less the rank of the fixed design), or KENWARDROGER, which also adjusts the fixed standard errors and F tests.

Tables: Model Dimension, Information Criteria (-2 log likelihood, AIC, AICC, CAIC, BIC; for REML only covariance parameters count), Type III Tests of Fixed Effects (Type I with SSTYPE(1), each effect after those before it) and Estimates of Covariance Parameters. PRINT adds SOLUTION (fixed estimates), TESTCOV (Wald Z and intervals for covariance parameters), G and R (one subject’s random and repeated covariance), COVB and CORB (fixed estimates, adjusted with KENWARDROGER), CPS (case counts), DESCRIPTIVES (cell statistics), HISTORY(n) (every n-th iteration, 1 by default, and the last) and LMATRIX (test coefficients). SOLUTION on RANDOM lists every subject’s predicted random effects with tests and intervals.

EMMEANS averages the fitted cells equally over the factors left out, covariates at their means or the WITH values; each mean and difference gets its own df. COMPARE tests every pair of levels, or each level against REFCAT, with LSD, BONFERRONI or SIDAK adjustment, plus an F test of the compared factor at each level of the others.

TEST takes coefficients for the parameters of named fixed effects (redundant ones included), or ALL of them; rows are separated by semicolons. Constants in parentheses are the tested values (0 by default); DIVISOR divides a row. ALL and effect names never mix in one TEST: the first decides the form. After | come coefficients for one subject’s random effects, by effect or as bare values over the RANDOM subcommands in order; bare values fit either form, and an effect on two RANDOM subcommands needs them. With SUBJECT they are shared among subjects, so the row tests their average. Each row gets an estimate and t test, plus a joint F test; a row with a non-estimable fixed part is dropped with a warning. A TEST with random effects keeps Satterthwaite df even with KENWARDROGER.

SAVE adds casewise variables: FIXPRED (fixed-part prediction), PRED (with the predicted random effects), RESID (dependent minus PRED), SEFIXP and DFFIXP (standard error and df of FIXPRED), SEPRED and DFPRED (the same for PRED). Default names are FXPRED_1, PRED_1, RESID_1, SEFIXP_1 and so on (first free number); a name in parentheses replaces it. Each is saved once, and an existing name is an error.

Example

MIXED yield BY plot_type WITH rain /FIXED=plot_type rain /RANDOM=INTERCEPT rain | SUBJECT(farm) COVTYPE(UN) /PRINT=SOLUTION TESTCOV.

statscraft help MIXED prints the same text in the terminal. All commands

Statscraft 0.61.0, release v0.61.0

VARCOMP

Variance components: how much each random effect of a linear model adds to the variance of the dependent variable.

Syntax

VARCOMP dependent BY factors [WITH covariates] /RANDOM=factor [factor ...] ...
   [/METHOD=MINQUE[(1 | 0)] | ML | REML | SSTYPE[(3 | 1)]] [/INTERCEPT=INCLUDE | EXCLUDE]
   [/MISSING=EXCLUDE | INCLUDE] [/REGWGT=var]
   [/CRITERIA=[CONVERGE(1E-8)] [EPS(1E-8)] [ITERATE(50)]]
   [/PRINT=[EMS] [SS] [HISTORY[(1)]]]
   [/OUTFILE=[VAREST] [COVB | CORB] ('file' | dataset)]
   [/DESIGN=[INTERCEPT] [effect ...]]

effects: a factor or covariate, a*b or a BY b, a(b) or a WITHIN b.

Every effect that holds a factor named on RANDOM is random, with its own variance; the other effects are fixed. RANDOM may repeat and its factors add up. Without DESIGN the model has the intercept, the covariates and every main effect and interaction of the factors.

The design is coded as in UNIANOVA: one indicator column per level combination that occurs.

METHOD picks the estimator. MINQUE (the default) solves the minimum norm quadratic unbiased equations with prior weight 1 for every random effect and the residual, or with 0 for the random effects and 1 for the residual. ML and REML maximize the full or the restricted likelihood, starting from the variance of each effect’s least squares estimates and the residual variance of the full model; Fisher scoring takes the first step and Newton steps follow while the Hessian allows, a step is halved up to 10 times until the likelihood rises, a variance that would turn negative is set to 0, and the fit stops when both the likelihood and the parameters change by less than CONVERGE (relative) or after ITERATE iterations. SSTYPE equates the mean square of each random effect and of the error, by Type I or III sums of squares, with its expected value and solves for the variances; these may come out negative. A case missing on any variable is left out; INCLUDE keeps user-missing values. The case weight is rounded and counts the case that many times; REGWGT weights the residual of each case (cases with a weight of 0 or less are left out). EPS is the tolerance for redundant design columns. Tables: Factor Level Information, Variance Estimates, with ML and REML the Asymptotic Covariance Matrix of the estimates (the inverse of the expected information); PRINT SS shows the sums of squares, df and mean squares and PRINT EMS the expected mean squares (SSTYPE only; the fixed effects that enter appear as a quadratic term); HISTORY(n) lists the log likelihood and the estimates at every n-th iteration and the last (ML and REML only). OUTFILE writes one row per component with its label (VarName_), its estimate (Estimate, with VAREST) and its row of the covariance or correlation matrix (COVB or CORB, ML and REML only) in columns VC1, VC2, …

Example

VARCOMP strength BY mixture batch operator /RANDOM=batch operator /METHOD=REML /PRINT=HISTORY.

statscraft help VARCOMP prints the same text in the terminal. All commands

Statscraft 0.61.0, release v0.61.0

GENLINMIXED

Generalized linear mixed model: a target with a normal, binomial, multinomial, gamma, inverse Gaussian, Poisson or negative binomial distribution and a link, fixed effects, random effects of subjects and repeated measures.

Syntax

GENLINMIXED [/DATA_STRUCTURE SUBJECTS=field[*field...] [REPEATED_MEASURES=field[*field...]]
          [COVARIANCE_TYPE=DIAGONAL | type]]
   /FIELDS TARGET=field [TRIALS=NONE | VALUE(n) | FIELD(field)] [ANALYSIS_WEIGHT=field]
          [OFFSET=NONE | VALUE(x) | FIELD(field)]
   [/TARGET_OPTIONS [REFERENCE=value]
          [DISTRIBUTION=NORMAL | BINOMIAL | MULTINOMIAL | GAMMA | INVERSE_GAUSSIAN | POISSON |
          NEGATIVE_BINOMIAL] [LINK=IDENTITY | CAUCHIT | CLOGLOG | LOG | LOGC | LOGIT | NLOGLOG |
          POWER | PROBIT] [LINK_PARAMETER=x]]
   [/FIXED [EFFECTS=effects] [USE_INTERCEPT=TRUE | FALSE]]
   [/RANDOM [EFFECTS=effects] [USE_INTERCEPT=FALSE | TRUE] [SUBJECTS=field[*field...]]
           [COVARIANCE_TYPE=type] [SOLUTION=FALSE | TRUE]] ...
   [/BUILD_OPTIONS [TARGET_CATEGORY_ORDER=ASCENDING | DESCENDING | DATA] [MAX_ITERATIONS=100]
          [CONFIDENCE_LEVEL=95] [DF_METHOD=RESIDUAL | SATTERTHWAITE | KENWARD_ROGER]
          [COVB=MODEL | ROBUST] [PCONVERGE=1E-6[(ABSOLUTE | RELATIVE)]] [LCONVERGE=0[(...)]]
          [HCONVERGE=0[(...)]] [SCORING=0] [SINGULAR=1E-12]]
   [/EMMEANS [TABLES=factor[*factor...]] [COMPARE=factor]
          [CONTRAST=NONE | PAIRWISE | DEVIATION | SIMPLE]] ...
   [/EMMEANS_OPTIONS [CONTROL=covariate(x) ...] [SCALE=ORIGINAL | TRANSFORMED]
          [PADJUST=LSD | SEQBONFERRONI | SEQSIDAK]]
   [/OUTFILE MODEL='file']
   [/SAVE [PREDICTED_VALUES[(name)]] [PREDICTED_PROBABILITY[(root)]] [MAX_CATEGORIES(25)]
          [CONFIDENCE[(name)]] [CONFIDENCE_METHOD(PREDICTEDPROBABILITY | PROBABILITYIMPROVEMENT)]
          [CONFIDENCE_INTERVALS[(root)]] [PEARSON_RESIDUALS[(name)]]]

effects: a field, a*b or a BY b, a(b); a field of scale level is a covariate, any other a factor.

type: VARIANCE_COMPONENTS (the default on RANDOM: one variance per effect; on DATA_STRUCTURE the same as DIAGONAL), IDENTITY, DIAGONAL, UNSTRUCTURED, COMPOUND_SYMMETRY, AR1, ARH1, ARMA11, CSH or TOEPLITZ, as the types of MIXED.

Without DISTRIBUTION a scale target is NORMAL, and one with TRIALS or a categorical one of two values BINOMIAL; the link defaults to IDENTITY, LOGIT, POWER(-1) for GAMMA, POWER(-2) for INVERSE_GAUSSIAN and LOG for POISSON and NEGATIVE_BINOMIAL. BINOMIAL takes either events with TRIALS or a target of two values; then the last value in TARGET_CATEGORY_ORDER (or REFERENCE) is the reference and the model is for the other one.

Cases whose target does not fit the distribution, or that miss a field, the offset or a weight above 0, are left out. The fit linearizes the model around the current means and fits the linear mixed model of the working target with the weights that follow from the variance function, by restricted likelihood as MIXED does, then updates the means with the predicted random effects, until no covariance parameter changes by more than PCONVERGE relative to its size. REPEATED_MEASURES orders the cases of each subject by these fields and lets their residuals be correlated as COVARIANCE_TYPE says; a model with neither is a generalized linear model of the fixed effects. The scale is 1 for BINOMIAL, POISSON and NEGATIVE_BINOMIAL without repeated measures and estimated otherwise; NORMAL with IDENTITY is MIXED itself. NEGATIVE_BINOMIAL takes its k from the model without random effects and keeps it. Each RANDOM must name subjects from DATA_STRUCTURE. MAX_ITERATIONS bounds both loops. COVB=ROBUST tests with the sandwich covariance over the subjects.

Tables: Model Summary, Model Dimension, Information Criteria (of the working model), Type III Tests of Fixed Effects, Estimates of Fixed Effects, Estimates of Covariance Parameters with standard errors and Wald intervals, and the predicted random effects of each RANDOM with SOLUTION=TRUE. Degrees of freedom are the cases less the rank of the fixed design unless DF_METHOD says otherwise. EMMEANS gives the means of a fixed effect of factors (the overall mean without TABLES) with covariates at their mean or CONTROL value, on the scale of the target or of the link, and with COMPARE the contrasts among the levels of one factor, adjusted by PADJUST, and their joint F test. SAVE adds the predicted mean (the events for events and trials, the category for a target of two values), its interval and the Pearson residual; probabilities and confidence need a categorical target. OUTFILE writes the fixed effects as a JSON model file.

A categorical target of three or more values is MULTINOMIAL. An ordinal one gets a threshold per category but the last in place of the intercept and a cumulative link (LOGIT, PROBIT, CLOGLOG, NLOGLOG or CAUCHIT); a nominal one is compared with its REFERENCE category (the last by default) by the logit, with its own parameters and random effects for each other category. Neither takes REPEATED_MEASURES; EMMEANS is ignored with a warning. SAVE gives the predicted category, the probabilities (cumulative for an ordinal target), the confidence and the intervals of the probabilities.

Example

GENLINMIXED /DATA_STRUCTURE SUBJECTS=clinic /FIELDS TARGET=cured /TARGET_OPTIONS DISTRIBUTION=BINOMIAL LINK=LOGIT /FIXED EFFECTS=dose /RANDOM USE_INTERCEPT=TRUE SUBJECTS=clinic.

statscraft help GENLINMIXED prints the same text in the terminal. All commands

Statscraft 0.61.0, release v0.61.0

COXREG

Cox proportional hazards regression of survival times, with strata, categorical covariates, stepwise selection and time-dependent covariates.

Syntax

COXREG [VARIABLES=] time [WITH var | var BY var | var TO var ...]
   /STATUS=var [EVENT] (values) [LOST (values)] [/STRATA=var]
   [/CATEGORICAL=varlist] [/CONTRAST(var)=DEVIATION[(ref)] | SIMPLE[(ref)] | DIFFERENCE |
   HELMERT | REPEATED | POLYNOMIAL[(metric)] | SPECIAL(matrix) | INDICATOR[(ref)]]
   [/METHOD=ENTER | FSTEP[(COND | LR | WALD)] | BSTEP[(COND | LR | WALD)] [ALL | terms]] ...
   [/MISSING=EXCLUDE | INCLUDE] [/PRINT=[DEFAULT] [SUMMARY] [BASELINE] [CORR] [CI[(95)]] [ALL]]
   [/CRITERIA=[BCON(1E-4)] [LCON(1E-5)] [ITERATE(20)] [PIN(0.05)] [POUT(0.1)]]
   [/PLOT=[NONE] [SURVIVAL] [HAZARD] [LML] [OMS]] [/PATTERN=var(value) ... [BY var]] ...
   [/SAVE=tempvar[(name)] ...] [/OUTFILE=[COEFF('file' | dataset)] [TABLE('file' | dataset)]] [/EXTERNAL].

tempvar: SURVIVAL SE HAZARD (or RESID) LML XBETA DFBETA PRESID. A case is used when time, status, strata and covariates are valid and its weight is positive; a negative time drops it, and so does a censored time earlier than every event of its stratum. Status values on the EVENT list mark an event; all others are censored (LOST changes nothing). String covariates are categorical; a categorical variable with k values becomes k - 1 coded columns that enter and leave together (DEVIATION, last category as reference, by default). Tied times follow Breslow. The fit is Newton-Raphson from all coefficients 0 on covariates centered at their means; it stops when no coefficient changes by BCON or more of its previous size, the log likelihood changes by less than LCON of its previous value, or after ITERATE iterations. Each METHOD starts from the model the one before it left: ENTER enters its terms, FSTEP enters by the score test (PIN) and removes by the chosen statistic (POUT), BSTEP enters its terms first and then removes and enters the same way. With no covariate only the beginning block and the baseline are shown. Tables: Case Processing Summary, Categorical Variable Codings, Omnibus Tests of Model Coefficients (block 0: -2 log likelihood; then per step the overall score test at all coefficients 0 and the changes from the previous step and block), Variables in the Equation (with PRINT CI the interval of Exp(B)), Model if Term Removed (COND and LR), Variables not in the Equation with the residual chi-square, and with PRINT the Correlation Matrix of Regression Coefficients, Covariate Means and a Survival Table per stratum: at every event time the baseline cumulative hazard with all covariates 0, and survival, its standard error and the cumulative hazard at the means. The baseline survival is the maximum likelihood estimate given the coefficients, so with no covariate it is the Kaplan-Meier curve. SUMMARY keeps a line per step in the Omnibus Tests and shows the other tables for the last step of each block only. String covariates tell their categories apart by their first eight bytes.

PLOT gives chart data of the step curves of each stratum at the means and at each PATTERN: named covariates at the values given, the others at their means; BY draws one line per category of a categorical covariate. SAVE adds, at each case’s own time and covariates, SUR_1, SE_1, HAZ_1, LML_1 and XBE_1 (the linear predictor with centered covariates), DFB1_1, DFB2_1, … (the change in each coefficient when the case is left out, from its score residual) and PRE1_1, PRE2_1, … for the Schoenfeld residuals of events, one per coded covariate and missing for those out of the final model, or the names given (DFBETA(name) gives name1, name2, …). Weighted when a weight variable is set. After a TIME PROGRAM, covariates it creates change with time; SAVE then gives DFBETA only and the survival table, PATTERN and plots are left out. EXTERNAL changes nothing.

OUTFILE writes each keyword to a .sav file or a dataset made with DATASET DECLARE. COEFF holds the final model: VARNAME_ (the coded column), B, SE, WALD, DF, SIG and EXPB, a record for each column, as in Variables in the Equation. TABLE holds the survival table of every stratum with a record for each event time: the strata variable (when there is one), TIME_, then SURVIVAL_, SE_ and HAZARD_ with the suffix 0 for the baseline (all covariates 0), M for the means, and the number of the line for each line of PATTERN (a BY line for each category); with a time program TABLE is not written.

Example

COXREG months WITH plan spend /STATUS=ended(1) /STRATA=site /CATEGORICAL=plan /PRINT=CI(95) BASELINE /PLOT=SURVIVAL.

statscraft help COXREG prints the same text in the terminal. All commands

Statscraft 0.61.0, release v0.61.0

TIME PROGRAM

Start the transformations that define time-dependent covariates for the next COXREG.

Syntax

TIME PROGRAM.

The transformations that follow (COMPUTE, IF, RECODE, DO IF, LOOP and the like), up to the next command of another kind, such as a label or format command, are kept for the next COXREG instead of changing the data. COXREG runs them for every case at each event time of its stratum up to the case’s own time, with the variable T_ holding that time, so a covariate they compute can change with time. The data may not have a variable T_, and T_ itself is not a covariate. A missing value from the program where the case is otherwise valid is an error, and so is a program that adds or drops cases, leaves a LOOP or DO IF open, or holds PRINT, WRITE or XSAVE; a COXREG that stops for a fault in the program drops it, one that stops for another error keeps it. Any other command that reads the data drops the program, as do CLEAR TIME PROGRAM and CLEAR TRANSFORMATIONS. A case the program gives a missing value while it is missing on a variable the program names is left out.

Example

TIME PROGRAM.
COMPUTE spend_t = spend * LN(T_ + 1).

statscraft help TIME PROGRAM prints the same text in the terminal. All commands

Statscraft 0.61.0, release v0.61.0

CLEAR TIME PROGRAM

Drop the time-dependent covariates of the last TIME PROGRAM.

Syntax

CLEAR TIME PROGRAM.

The transformations of the last TIME PROGRAM are dropped, so a new TIME PROGRAM can define the time-dependent covariates afresh. COXREG uses a program up when it runs, and so does any other command that reads the data.

Example

CLEAR TIME PROGRAM.

statscraft help CLEAR TIME PROGRAM prints the same text in the terminal. All commands

Statscraft 0.61.0, release v0.61.0

ANOVA

Analysis of variance for factorial designs with covariates, the older form with MCA tables.

Syntax

ANOVA [VARIABLES=] dependents BY factors(min,max) [factors(min,max) ...] [WITH covariates] [/next list ...]
      [/COVARIATES=FIRST | WITH | AFTER] [/MAXORDERS=ALL | n | NONE]
      [/METHOD=UNIQUE | EXPERIMENTAL | HIERARCHICAL] [/STATISTICS=[MCA] [REG] [MEAN] [ALL] [NONE]]
      [/MISSING=EXCLUDE | INCLUDE].

A range follows the factors it applies to; factor values are truncated to whole numbers and cases outside a range are left out, as is a case missing on any variable of its list. The model has the covariates, the main effects and the interactions up to MAXORDERS (five by default); an order of interactions with empty cells is dropped with a warning. UNIQUE (default) adjusts every effect for all others (Type III); EXPERIMENTAL assesses covariates, main effects and each order of interactions in turn, each adjusted for its own kind and the kinds before it; HIERARCHICAL adjusts each covariate and factor only for those before it. COVARIATES sets where the covariates enter. Tables: ANOVA (with REG the coefficients of the covariates where they enter), and, not with UNIQUE, Cell Means (MEAN), MCA, Factor Summary and Model Goodness of Fit (MCA). STATISTICS without keywords is MEAN and REG. Weighted when a weight variable is set.

Example

ANOVA VARIABLES=score BY region(1,4) sex(1,2) WITH age /METHOD=EXPERIMENTAL /STATISTICS=MEAN MCA.

statscraft help ANOVA prints the same text in the terminal. All commands

Statscraft 0.61.0, release v0.61.0

TREE

A decision tree grown by CHAID, exhaustive CHAID, CRT or QUEST, with gain tables, rules and saved predictions.

Syntax

TREE dependent [level] BY predictor [level] ... [FORCE = var [level]]
     [/METHOD TYPE=CHAID | EXHAUSTIVECHAID | CRT | QUEST  MAXSURROGATES=AUTO | n  PRUNE=NONE | SE[(b)]]
     [/GROWTHLIMIT MAXDEPTH=AUTO | n  MINPARENTSIZE=100  MINCHILDSIZE=50  MINIMPROVEMENT=0.0001]
     [/CHAID ALPHASPLIT=.05 ALPHAMERGE=.05 SPLITMERGED=NO | YES CHISQUARE=PEARSON | LR CONVERGE=.001
             MAXITERATIONS=100 ADJUST=BONFERRONI | NONE INTERVALS=10 | varlist(n) ...]
     [/CRT IMPURITY=GINI | TWOING | ORDEREDTWOING  MINIMPROVEMENT=0.0001]  [/QUEST ALPHASPLIT=.05]
     [/PRIORS FROMDATA | EQUAL | CUSTOM=value [prior] ...  ADJUST=NO | YES]
     [/COSTS EQUAL | CUSTOM=actual predicted [cost] ...]  [/SCORES EQUALINCREMENTS | CUSTOM=value [score] ...]
     [/PROFITS CUSTOM=category [revenue expense] ...]  [/TARGETRESPONSE RATE=NONE | percent]
     [/INFLUENCE var]
     [/DEPCATEGORIES USEVALUES=[VALID MISSING value ...] TARGET=[value ...]]
     [/VALIDATION TYPE=NONE | SPLITSAMPLE(percent | var) | CROSSVALIDATION(folds)  OUTPUT=BOTHSAMPLES | TESTSAMPLE]
     [/MISSING NOMINALMISSING=MISSING | VALID]
     [/TREE DISPLAY=TOPDOWN | NONE  BRANCHSTATISTICS=YES | NO  NODEDEFS=YES | NO]
     [/PRINT=MODELSUMMARY CLASSIFICATION RISK CPS TREETABLE IMPORTANCE SURROGATES | NONE]
     [/GAIN SUMMARYTABLE=YES | NO  CATEGORYTABLE=YES | NO  TYPE=[NODE PTILE]  SORT=DESCENDING | ASCENDING
            INCREMENT=10  CUMULATIVE=YES | NO]
     [/PLOT GAIN RESPONSE INDEX MEAN PROFIT ROI IMPORTANCE INCREMENT=10]
     [/RULES NODES=TERMINAL | ALL | TOPN(n) | TOPPCT(p) | MININDEX(v) | NONE  SYNTAX=INTERNAL | SQL | GENERIC
             TYPE=SCORING | SELECTION  SURROGATES=INCLUDE | EXCLUDE  LABELS=YES | NO  OUTFILE='file']
     [/SAVE NODEID[(name)] PREDVAL[(name)] PREDPROB[(root)]].

The command splits the cases, again and again, by the predictor that best separates the values of the dependent, then shows the tree, its risk and how well it classifies. METHOD TYPE picks the method: CHAID (the default) and EXHAUSTIVECHAID may split a node into more than two children, CRT and QUEST always split in two. A level after a variable sets how it is read: [S] scale, [O] ordinal, [N] or [C] nominal. Without one the dictionary’s level holds, and a variable with no level gets one from its values. The default PRINT is MODELSUMMARY CLASSIFICATION RISK CPS.

CHAID takes a nominal dependent (Pearson chi-square, or the likelihood ratio with CHISQUARE=LR), an ordinal one (row effects model, scored 1, 2, … or by SCORES CUSTOM) or a scale one (F test). Scale predictors are cut into INTERVALS groups of about equal size (at most 64; varlist(n) sets n per variable). Categories of a predictor that do not differ at ALPHAMERGE are merged, ordinal ones only with a neighbor, and with SPLITMERGED=YES a merged group of three or more categories is split in two again where that split is significant at ALPHAMERGE; exhaustive CHAID merges down to two and keeps the most significant grouping. A missing value is a category that may join any other. A category smaller than MINCHILDSIZE joins its closest neighbor. The predictor with the smallest Bonferroni-adjusted p-value (ADJUST=NONE: unadjusted) splits the node if that is at most ALPHASPLIT. FORCE=var splits the root by var.

INFLUENCE names a numeric variable that says how much each case counts in growing a CHAID or CRT tree. CHAID’s tests of independence use expected counts adjusted by the mean influence of each cell, and its F test of a scale dependent counts each case influence times as often; CRT counts each case as influence times frequency in its priors, impurities, improvements and surrogates, and its PRIORS FROMDATA are the shares of those counts. A node’s class (a scale dependent’s: its mean) is the one with the most influence times frequency. A case whose influence is missing, zero or negative is left out. Node sizes, counts, risk and gains still count frequencies only. QUEST ignores it with a warning.

A node is not split when it is pure, holds fewer than MINPARENTSIZE cases or is at MAXDEPTH (AUTO: 3 for CHAID, 5 for CRT and QUEST). MINCHILDSIZE must be less than MINPARENTSIZE. A weight counts each case as often as its rounded value. SPLIT FILE is ignored.

CRT takes a nominal, ordinal or scale dependent. It tries every cut of a scale or ordinal predictor (x <= v goes left) and every split of a nominal one’s categories in two, and keeps the split that lowers the impurity most. IMPURITY is GINI, TWOING or ORDEREDTWOING (ordinal dependent only). A node also stops when the best improvement is below MINIMPROVEMENT. For a scale dependent the impurity is the variance within the node, a node predicts its mean, the risk is the mean squared deviation, and PRIORS, COSTS and the class tables do not apply.

QUEST needs a nominal dependent and reads scale and ordinal predictors as numbers. A node splits on the predictor whose test against the classes (F or chi-square) has the smallest p-value, if that is below ALPHASPLIT divided by the number of predictors; otherwise a test of spread may still split it. The cut comes from a discriminant analysis of the classes grouped in two. The tree table shows each split’s test, p-value and cut.

For CRT and QUEST, PRIORS FROMDATA (the default), EQUAL or CUSTOM=value [prior] … gives the class probabilities that decide each node’s class and weigh the risk. A case missing the split variable follows the first surrogate it has a value for (a split of another predictor that mimics the main one), else the larger child. MAXSURROGATES caps the surrogates (AUTO: one fewer than the predictors; 0: none), and PRINT SURROGATES lists them. PRUNE=SE(b) (b is 1 when left out) cuts the tree back to the smallest subtree whose risk is within b standard errors of the lowest. PRINT and PLOT IMPORTANCE (CRT only) show each predictor’s improvement relative to the largest.

COSTS CUSTOM=actual predicted [cost] … sets the cost of predicting one category for a case of another: 1 when not given, and a correct prediction always costs 0. A node gets the category with the least expected cost, and the risk is the mean cost. CRT with GINI also grows the tree by the costs. PRIORS ADJUST=YES instead folds the costs into the priors and then ignores them. A setting that does not apply to the method or the dependent, such as PRIORS under CHAID or SCORES under CRT, is ignored with a warning.

VALIDATION TYPE=SPLITSAMPLE(percent) grows the tree on a random share of the cases (50 when no number is given; SET SEED repeats it) and tests it on the rest; SPLITSAMPLE(var) trains on the cases where var is 1. Risk, classification and gains are shown for both samples (OUTPUT=TESTSAMPLE: the test sample only), and PRUNE uses the test sample’s risk. CROSSVALIDATION(folds) (2 to 25, default 10) adds a cross-validated risk without changing the tree; it is ignored with FORCE.

The tree comes as chart data: each node with its parent, the condition that leads to it, its counts, its predicted value and its split. DISPLAY=NONE leaves it out, and TREETABLE lists the nodes as a table. USEVALUES lists the classes of the dependent (VALID: every valid value; user-missing values of a nominal dependent may be named). NOMINALMISSING=VALID makes user-missing values of nominal predictors valid categories.

Gain tables, one per TARGET category, list the terminal nodes by index: size, target count, response (the target share in the node) and index (response over the overall share), cumulative unless CUMULATIVE=NO. TYPE=[NODE PTILE] adds percentile groups INCREMENT percent wide (1, 2, 5, 10, 20 or 25; default 10). For a scale dependent SUMMARYTABLE lists the nodes by mean. PLOT GAIN, RESPONSE and INDEX chart the percentile groups. PROFITS CUSTOM=category [revenue expense] … adds the average profit and the return on investment to the summary, charted by PLOT PROFIT and ROI. PLOT MEAN charts a scale dependent.

TARGETRESPONSE (a nominal or ordinal dependent with TARGET categories on DEPCATEGORIES; RATE is required) gives for each target category and sample a Target Response table: the terminal nodes by the percentage of the category in them, the highest first, each with the conditions of its path (a missing value is left out, and a CHAID node that stands for a missing category alone is not listed) and the cumulative percentage down the table, with RATE=percent also whether that reaches the percentage; and a chart of the cumulative percentages, with the percentage as a line.

RULES writes rules for the terminal nodes (NODES=ALL: every node, parents first). SYNTAX=INTERNAL gives DO IF blocks that compute NodeID, PredictedValue and PredictedProbability, SQL gives CASE expressions, GENERIC gives sentences with labels (LABELS=NO: names and values). TYPE=SELECTION gives one rule that selects the cases of the nodes. A missing value follows the surrogates (SURROGATES=INCLUDE), then the larger child. TOPN(n), TOPPCT(p) and MININDEX(v) keep the terminal nodes with the highest index. OUTFILE writes the rules to a text file.

SAVE adds the terminal node, the predicted value and one probability per category (default names NodeID, PredictedValue and PredictedProbability_1, …), for test cases too. A scale dependent saves the node mean as PREDVAL. DMTREE is another name for the command.

Example

GET FILE='survey.sav'.
TREE recommend [n] BY satisfaction [o] region [n] age_group [o] contacted [n]
  /GROWTHLIMIT MAXDEPTH=2 MINPARENTSIZE=40 MINCHILDSIZE=20 /SAVE NODEID PREDVAL.
TREE switching [n] BY satisfaction [o] region age_group spend [s]
  /METHOD TYPE=CRT /GROWTHLIMIT MAXDEPTH=3 /PRINT=MODELSUMMARY RISK IMPORTANCE.

The example reads the sample data file survey.sav, an invented customer survey; save it in the folder you run the syntax from.

statscraft help TREE prints the same text in the terminal. All commands

Statscraft 0.61.0, release v0.61.0

DMTREE

Another name for TREE.

Syntax

DMTREE dependent BY predictors [/subcommands of TREE].

The same command as TREE, with the same subcommands and defaults.

Example

DMTREE bought [n] BY region [n] age_group [o] /GROWTHLIMIT MAXDEPTH=2.

statscraft help DMTREE prints the same text in the terminal. All commands

Statscraft 0.61.0, release v0.61.0

MLP

Multilayer perceptron: a neural network with one or two hidden layers that predicts scale dependents and classifies categorical ones.

Syntax

MLP dependent [(MLEVEL=S | O | N)] [dependent ...] [BY factors] [WITH covariates]
   [/EXCEPT VARIABLES=varlist]
   [/RESCALE [COVARIATE=STANDARDIZED | NORMALIZED | ADJNORMALIZED | NONE]
             [DEPENDENT=STANDARDIZED | NORMALIZED [(CORRECTION=0.02)] | ADJNORMALIZED [(CORRECTION=0.02)] | NONE]]
   [/PARTITION TRAINING=70 TESTING=30 HOLDOUT=0 | VARIABLE=var]
   [/ARCHITECTURE [AUTOMATIC=YES [(MINUNITS=1, MAXUNITS=50)] | NO]
                  [HIDDENLAYERS=1 | 2 [(NUMUNITS=AUTO | n [, n])]] [HIDDENFUNCTION=TANH | SIGMOID]
                  [OUTPUTFUNCTION=IDENTITY | SIGMOID | SOFTMAX | TANH]]
   [/CRITERIA [TRAINING=BATCH | ONLINE | MINIBATCH] [MINIBATCHSIZE=AUTO | n] [MEMSIZE=1000]
              [OPTIMIZATION=GRADIENTDESCENT | SCALEDCONJUGATE] [LEARNINGINITIAL=0.4]
              [LEARNINGLOWER=0.001] [MOMENTUM=0.9] [LEARNINGEPOCHS=10] [LAMBDAINITIAL=0.0000005]
              [SIGMAINITIAL=0.00005] [INTERVALCENTER=0] [INTERVALOFFSET=0.5]]
   [/STOPPINGRULES [ERRORSTEPS=1 [(DATA=AUTO | BOTH)]] [TRAININGTIMER=ON [(MAXTIME=15)] | OFF]
                   [MAXEPOCHS=AUTO | n] [ERRORCHANGE=0.0001] [ERRORRATIO=0.001]]
   [/MISSING USERMISSING=EXCLUDE | INCLUDE]
   [/PRINT [CPS] [NETWORKINFO] [SUMMARY] [CLASSIFICATION] [SOLUTION] [IMPORTANCE] [NONE]]
   [/PLOT [NETWORK] [PREDICTED] [RESIDUAL] [ROC] [GAIN] [LIFT] [NONE]]
   [/SAVE [PREDVAL[(names)]] [PSEUDOPROB[(root[:25] ...)]]] [/OUTFILE MODEL='file' ...].

Keywords are written in full and each subcommand comes once. A dependent is scale or categorical by MLEVEL, else by its measurement level; categorical dependents and factors get one unit per category of the training cases. Cases missing on any variable are left out (user-missing values of categorical variables count with INCLUDE); the rest go to training, testing and holdout at random by the shares (SET SEED makes it repeatable), or by the sign of the VARIABLE: positive trains, 0 tests, negative holds out. Covariates and scale dependents are rescaled by the training cases. Hidden units use TANH (default) or SIGMOID; the output units IDENTITY when a dependent is scale, else SOFTMAX with cross-entropy error; other outputs use the sum of squares. SIGMOID outputs need NORMALIZED dependents and TANH outputs ADJNORMALIZED, the defaults for them. AUTOMATIC=YES (default) uses one TANH layer and searches the number of units between MINUNITS and MAXUNITS on a sample of at most MEMSIZE (and 1000) cases, removing the weakest unit or adding one while the testing error drops.

NUMUNITS=AUTO starts from a count based on the numbers of input and output units and of training cases. Starting weights come from random draws in INTERVALCENTER +- INTERVALOFFSET, trained and shaken by simulated annealing on that sample. BATCH training uses SCALEDCONJUGATE by default; ONLINE and MINIBATCH use GRADIENTDESCENT on the cases in a random order, the learning rate falling from LEARNINGINITIAL to LEARNINGLOWER over LEARNINGEPOCHS passes. Training stops when the error (testing cases when there are any) has not reached a new low for ERRORSTEPS steps, at MAXTIME minutes, after MAXEPOCHS passes (AUTO: twice the weights plus 1, at least 100), or when the training error changes by less than ERRORCHANGE or falls below ERRORRATIO times that of predicting the means; the weights kept are those of the lowest error. Tables: Case Processing Summary (CPS), Network Information, Model Summary with the error, the relative error or percent incorrect and the rule that stopped training (SUMMARY), Classification per categorical dependent, Parameter Estimates (SOLUTION) and Independent Variable Importance with a chart (IMPORTANCE). Charts: the units of the network (NETWORK, default), predicted by observed (PREDICTED), residual by predicted (RESIDUAL), ROC with the areas, cumulative gains and lift of each category, from the training and testing cases. SAVE adds the predicted value or category (MLP_PredictedValue) and the first n outputs of each categorical dependent (MLP_PseudoProbability_1, …). OUTFILE writes Statscraft’s own JSON model, one file per dependent, not with SPLIT FILE. The weight variable is not used.

Example

SET SEED=20251.
MLP churned (MLEVEL=N) BY plan region WITH tenure spend
  /PARTITION TRAINING=6 TESTING=2 HOLDOUT=2 /ARCHITECTURE AUTOMATIC=NO HIDDENLAYERS=1 (NUMUNITS=4)
  /PRINT CPS NETWORKINFO SUMMARY CLASSIFICATION IMPORTANCE /PLOT ROC /SAVE PREDVAL PSEUDOPROB.

statscraft help MLP prints the same text in the terminal. All commands

Statscraft 0.61.0, release v0.61.0

RBF

Radial basis function network: Gaussian hidden units at two-step clusters and least squares output weights.

Syntax

RBF dependent [(MLEVEL=S | O | N)] [dependent ...] [BY factors] [WITH covariates]
   [/EXCEPT VARIABLES=varlist]
   [/RESCALE [COVARIATE=STANDARDIZED | NORMALIZED | ADJNORMALIZED | NONE]
             [DEPENDENT=STANDARDIZED | NORMALIZED | ADJNORMALIZED | NONE]]
   [/PARTITION TRAINING=70 TESTING=30 HOLDOUT=0 | VARIABLE=var]
   [/ARCHITECTURE [MINUNITS=AUTO | n MAXUNITS=AUTO | n | NUMUNITS=n] [HIDDENFUNCTION=NRBF | ORBF]]
   [/CRITERIA OVERLAP=AUTO | number] [/MISSING USERMISSING=EXCLUDE | INCLUDE]
   [/PRINT [CPS] [NETWORKINFO] [SUMMARY] [CLASSIFICATION] [SOLUTION] [IMPORTANCE] [NONE]]
   [/PLOT [NETWORK] [PREDICTED] [RESIDUAL] [ROC] [GAIN] [LIFT] [NONE]]
   [/SAVE [PREDVAL[(names)]] [PSEUDOPROB[(root[:25] ...)]]] [/OUTFILE MODEL='file' ...].

Variables, missing values, partitions, rescaling (STANDARDIZED by default for scale dependents too), tables, charts, SAVE (RBF_PredictedValue, RBF_PseudoProbability) and OUTFILE work as in MLP. The training cases are clustered by the two-step method (covariates as continuous, factors as categorical variables). Each hidden unit is a Gaussian at a cluster’s means and category shares, its width the square root of OVERLAP (AUTO: 1 + 0.1 per input unit) times the root mean square of the cluster’s standard deviations and of p(1 - p) for categories. NRBF (default) divides the units by their sum; ORBF keeps them and adds a bias. The output weights are least squares, with identity outputs and the sum of squares error for every dependent. Without NUMUNITS the number of units is searched between MINUNITS and MAXUNITS (AUTO: from the two-step cluster count K and the R output units, min(K, R), at least 2 for NRBF, to max(10, 2K, R)): the lowest error of the testing cases wins, or without them the lowest BIC of the training cases. The weight variable is not used.

Example

SET SEED=4417.
RBF spend BY plan WITH tenure visits /ARCHITECTURE HIDDENFUNCTION=ORBF
  /PRINT CPS NETWORKINFO SUMMARY SOLUTION /PLOT PREDICTED RESIDUAL /SAVE PREDVAL(spend_hat).

statscraft help RBF prints the same text in the terminal. All commands

Statscraft 0.61.0, release v0.61.0

GRAPH

One chart: summaries by category as bars, lines, areas, a pie, points with error bars, a Pareto chart or ranges, a histogram, a scatterplot or a scatterplot matrix.

Syntax

GRAPH [/TITLE='line' ['line']] [/SUBTITLE='line'] [/FOOTNOTE='line' ['line']]
      /BAR[(SIMPLE | GROUPED | STACKED | RANGE)]=spec | /PIE=spec
      | /LINE[(SIMPLE | MULTIPLE | AREA | DROP | DIFFERENCE)]=spec | /HILO[(SIMPLE | GROUPED)]=spec
      | /PARETO[(CUM | NOCUM)][(SIMPLE | STACKED)]=spec
      | /ERRORBAR[(CI [95] | STERROR [2] | STDDEV [2])]=varlist [BY var] | var BY var BY var
      | /HISTOGRAM[(NORMAL)]=var
      | /SCATTERPLOT[(BIVARIATE | OVERLAY | MATRIX | XYZ)]=x WITH y | xlist WITH ylist [(PAIR)]
          | varlist | x WITH y WITH z, then [BY group] [BY id (NAME | IDENTIFY)]
      [/INTERVAL CI[(95)] | SE[(2)] | STDDEV[(2)]]
      [/PANEL [COLVAR=varlist [COLOP=CROSS | NEST]] [ROWVAR=varlist [ROWOP=CROSS | NEST]]]
      [/TEMPLATE='file']
      [/MISSING=[LISTWISE | VARIABLE] [NOREPORT | REPORT] [EXCLUDE | INCLUDE]].

The command draws one chart. The first subcommand needs no slash, and keywords may be cut to three letters (MIN, MAX, ERR, STE). A spec is COUNT, PCT, CUFREQ or CUPCT BY var [BY var]; a bare variable (COUNT BY var); func(varlist) [BY var [BY var]]; or VALUE(varlist) [BY var]. The functions are MEAN, MEDIAN, GMEDIAN, MODE, SUM, CUSUM, N, MINIMUM, MAXIMUM, STDDEV, VARIANCE, PTILE(varlist, p), PLT, PGT, NLT, NGT(varlist, x), PIN and NIN(varlist, low, high). SUM(a b) means SUM(a) SUM(b).

The spec sets the layout. One function by one variable gives one series; by two variables, a series per value of the second. Several functions give a series each by one variable, or one bar or slice each without BY. SIMPLE, GROUPED and MULTIPLE change nothing; STACKED stacks the series and AREA fills and stacks them. A pie takes one series.

COUNT and N add up the case weights; PCT is a share of all cases in the chart. CUFREQ, CUSUM and CUPCT add up along each series (CUPCT ends at 100). PLT, PGT and PIN give the share of valid values below x, above x or from low to high; NLT, NGT and NIN the weighted count. MEDIAN and PTILE work as in FREQUENCIES, MODE takes the smallest tied value, and GMEDIAN treats values as group midpoints. VALUE draws an unweighted bar per case and a series per variable; a missing value leaves a gap and the BY variable names the cases.

Categories ascend by value. A case missing a category value is left out unless MISSING=REPORT, which adds missing categories after the valid ones. LISTWISE drops a case missing on any function variable; VARIABLE drops it only from that variable’s functions. INCLUDE makes user-missing values valid. Categories empty in every series are left out; at most 3000 categories. Cases with a zero or missing weight are left out. SPLIT FILE gives a chart per group.

ERRORBAR shows each mean as a point with a bar, laid out as MEAN(varlist). CI (the default, level 95, from 50 to 99.9) uses Student’s t with W - 1 degrees of freedom; STERROR (or SE) and STDDEV reach n (default 2) standard errors or deviations each way. A mean whose cases weigh 1 or less gets no bar. INTERVAL adds such bars to a simple or clustered bar or line chart of MEAN, or of MEDIAN with CI only. A median’s interval comes from interpolated order statistics, need not be symmetric and needs whole case weights.

PARETO counts or sums (COUNT, a bare variable, SUM or VALUE), largest category first, several series stacked. CUM, the default, adds the running total as a percentage line on a right axis from 0 to 100; NOCUM leaves it off. BAR(RANGE) floats a bar between two series (two functions, or a second BY variable with two values). LINE(DROP) joins the lowest and highest series of each category, LINE(DIFFERENCE) shades between two series, and HILO takes high, low and an optional close as two or three series. More series make a grouped chart, each group beside the next in a category: a function of two or three variables is a group (MEAN(a b c) MEAN(d e f)), and functions of one variable group by the order they repeat in (MAX(x) MIN(x) MAX(y) MIN(y)).

HISTOGRAM bins the valid values as FREQUENCIES does; NORMAL adds the normal curve. SCATTERPLOT colors points by the BY group variable; BY id (NAME) labels them with the id values, (IDENTIFY) does not. Lists around WITH put every pair into one frame (with PAIR, first with first and so on, and no BY group), the variable before WITH across. A list without WITH draws a matrix with the names on the diagonal. x WITH y WITH z has a third axis and shows as a table of its points. LISTWISE needs a case valid on all variables; VARIABLE needs it valid on the pair.

PANEL repeats the chart for each combination of ROWVAR and COLVAR categories, rows first, each named in its title. Empty combinations get no chart, so COLOP and ROWOP change nothing. A case missing on a panel variable is left out unless REPORT. TITLE names the chart (by default after its content), SUBTITLE goes under it and FOOTNOTE below. TITLE and FOOTNOTE take up to two lines, SUBTITLE one, each at most 72 characters. TEMPLATE is ignored; charts come as data.

Example

GRAPH /TITLE='Visits per store' /BAR(STACKED)=COUNT BY store BY daypart.

statscraft help GRAPH prints the same text in the terminal. All commands

Statscraft 0.61.0, release v0.61.0

GGRAPH

A chart from a graph dataset and a chart program in BEGIN GPL: bars (clustered, stacked), lines, areas, points, a pie or a histogram.

Syntax

GGRAPH /GRAPHDATASET NAME="name" VARIABLES=item ... [TRANSFORM=NO | VARSTOCASES(SUMMARY="n" INDEX="n" [HIGH="n" LOW="n"])]
              [MISSING=LISTWISE | VARIABLEWISE] [REPORTMISSING=NO | YES] [CASELIMIT=n]
       /GRAPHSPEC SOURCE=INLINE [LABEL="text"].

BEGIN GPL chart program END GPL.

item: a variable (ALL and TO allowed) with an optional [NAME=“new” LEVEL=SCALE | NOMINAL | ORDINAL], or a function with an optional [NAME=“new”]: COUNT(), MINIMUM MAXIMUM VALIDN SUM MEAN STDDEV VARIANCE MEDIAN GMEDIAN MODE (var), PTILE GPTILE PLT PGT NLT NGT NLE PLE NEQ PEQ NGE PGE (var, x), PIN NIN (var, low, high), CASEVALUE(var). The interval functions MEANCI MEDIANCI (var, level), MEANSD MEANSE (var, k) and COUNTCI(level) give a value and the two ends of its interval, as the error bars of GRAPH compute them: a level runs from 50 up to but below 100, k is a whole number above 0, and the ends are columns named like the function with _HIGH and _LOW added; [NAME=“v” HIGH=“h” LOW=“l”] renames them. Keywords are written in full. A function makes one row per combination of the other variables’ values; its column is called by its name and arguments joined with underscores (MEAN_price, PTILE_price_90) unless NAME renames it. Without a function every case with a positive weight is a row, and $CASENUM numbers them. Weights count in every function.

GMEDIAN and GPTILE take each value as the midpoint of its interval and interpolate on the cumulative weights; a percentile below the first midpoint or above the last is missing.

LISTWISE drops a case missing on any listed variable; VARIABLEWISE drops it only from the functions of the variable it misses. REPORTMISSING=YES turns user-missing values of variables that are not at the scale level into categories of their own. VARSTOCASES makes a row of each function, numbered in the INDEX column with the value in the SUMMARY column, and the ends of an interval function in the HIGH and LOW columns (#HIGH and #LOW unless named; missing for a function without an interval).

CASELIMIT keeps the first n rows.

Each GRAPHSPEC takes the next BEGIN GPL block; both stand right after the command. In the chart program: SOURCE: s=userSource(id(“name”)); DATA: x=col(source(s), name(“column”) [, unit.category()]); GUIDE: axis(dim(1 | 2), label(“text”) | null()), legend(aesthetic(…), label(“text”)), text.title, text.subtitle, text.footnote(label(“text”)); SCALE: linear(dim(2), include(0), max(n)), cat(dim(n) | aesthetic(…), include(“value”, …)), which adds categories; COORD: rect(dim(1,2), cluster(3)) clusters, transpose() lays bars across, polar.theta() makes a pie; ELEMENT: interval, interval.dodge, interval.stack, line, area, area.stack or point with position(x*y) or position(x*y*z) with cluster, and color(variable) for a series per category or color(“name”) to name the series. Several rows on one point need summary.count, mean, sum, median, mode, min, max or percent around the position; position(summary.count(bin.rect(x))) is a histogram and line(position(density.normal(x))) adds its normal curve. point over two scale variables is a scatterplot. interval(position(region.spread.range(x*(low+high)))), with shape(shape.ibeam) allowed, adds error bars around the values of the other element over the same categories. Other statements and settings give a warning and are skipped.

Example

GGRAPH /GRAPHDATASET NAME="sales" VARIABLES=store daypart MEAN(basket)
  /GRAPHSPEC SOURCE=INLINE.
BEGIN GPL
SOURCE: s=userSource(id("sales"))
DATA: store=col(source(s), name("store"), unit.category())
DATA: daypart=col(source(s), name("daypart"), unit.category())
DATA: basket=col(source(s), name("MEAN_basket"))
GUIDE: axis(dim(2), label("Average basket"))
ELEMENT: interval.stack(position(store*basket), color(daypart))
END GPL.

statscraft help GGRAPH prints the same text in the terminal. All commands

Statscraft 0.61.0, release v0.61.0

BEGIN GPL

The chart program of the GGRAPH command right before it, up to END GPL.

Syntax

BEGIN GPL

chart program END GPL.

BEGIN GPL and END GPL each stand alone on their line. The block belongs to the GGRAPH before it (one block for each GRAPHSPEC with SOURCE=INLINE); see GGRAPH for the statements it reads.

Example

BEGIN GPL
SOURCE: s=userSource(id("sales"))
DATA: price=col(source(s), name("price"))
ELEMENT: interval(position(summary.count(bin.rect(price))))
END GPL.

statscraft help BEGIN GPL prints the same text in the terminal. All commands

Statscraft 0.61.0, release v0.61.0

IGRAPH

The older chart command: bars, lines, areas, pies, boxes, error bars, histograms and scatterplots built from variables placed on axes and legends.

Syntax

IGRAPH [/Y=VAR(var) | $COUNT | $PCT [TYPE=SCALE [(MIN=n MAX=n)] | CATEGORICAL] [TITLE='text']]
       [/X1=VAR(var) | $CASE [TYPE=...] [TITLE='text']] [/X2=VAR(var) [TYPE=...] [TITLE='text']]
       [/COLOR=VAR(var) [TYPE=...] [LEGEND=ON | OFF] [TITLE='text'] [CLUSTER | STACK]]
       [/STYLE=VAR(var) [LEGEND=ON | OFF] [TITLE='text'] [CLUSTER | STACK]] [/SIZE=VAR(var) ...]
       [/SUMMARYVAR=VAR(var) | $COUNT | $PCT] [/STACK=VAR(var)] [/PANEL VAR(var) [VAR(var) ...]]
       [/CATORDER VAR(var) ([ASCENDING | DESCENDING] [VALUE | LABEL | COUNT | OCCURRENCE]
           [OMITEMPTY | SHOWEMPTY])] [/POINTLABEL=VAR(var) [ALL | NONE]] [/CASELABEL=VAR(var)]
       [/COORDINATE=VERTICAL | HORIZONTAL | THREE] [/NORMALIZE] [/TITLE='text'] [/SUBTITLE='text']
       [/CAPTION='text'] [/VIEWNAME='text'] [/MISSING=[LISTWISE | VARIABLEWISE] [NOREPORT | REPORT]
           [EXCLUDE | INCLUDE]]
       /BAR [(function)] | /LINE [(function)] | /AREA [(function)] | /PIE [(function)]
       | /BOX [OUTLIERS=ON | OFF] [EXTREME=ON | OFF] | /ERRORBAR CI(level) | SD(n) | SE(n)
       | /HISTOGRAM [CUM] [CURVE=ON | OFF] | /SCATTER [/FITLINE METHOD=REGRESSION LINEAR
           | ORIGIN LINEAR | MEAN | NONE [LINE=TOTAL MEFFECT]].

function: MEAN MEDIAN MODE MINIMUM MAXIMUM SUM SUMAV SUMSQ STDDEV VARIANCE SEMEAN SKEW KURTOSIS SESKEW SEKURT FIRST LAST, PTILE(p), NLT NLE NEQ NGE NGT(x), PLT PLE PEQ PGE PGT(x), NIN PIN(low, high). A variable may also be written without VAR( ).

Each chart is drawn as GRAPH would draw it. BAR, LINE and AREA put the categories of X1 along the axis and a summary of Y on the other: the function given (MEAN when none is) of a Y variable, or the count or percentage of cases with Y=$COUNT or $PCT. A categorical COLOR or STYLE variable gives a series per category, clustered unless STACK is given; NORMALIZE then stacks to 100%.

X1=$CASE draws a bar per case, named by the CASELABEL variable. A Y variable of TYPE=CATEGORICAL takes MODE only. ERRORBAR alone draws means of Y with bars of a confidence interval or of n standard deviations or errors; given with BAR or LINE it adds those bars to the means.

PIE takes its slices from the COLOR (or STYLE) categories, sized by SUMMARYVAR: $COUNT (the default), $PCT, or a variable with a function such as PIE (SUM). X1, Y and STACK variables give a separate pie per category, as PANEL does.

BOX draws Tukey boxes of Y per category of X1, side by side per COLOR category: hinges, median, whiskers to the furthest values within 1.5 box lengths, outliers beyond them and extremes beyond 3 box lengths, each marked by case number. OUTLIERS=OFF and EXTREME=OFF leave those marks out. HISTOGRAM bins X1 with automatic widths as GRAPH does; Y=$PCT shows percentages, CUM running totals and CURVE=ON the normal curve.

SCATTER plots Y against X1, a group per COLOR or STYLE category; a scale X2 adds a third axis.

POINTLABEL with ALL labels the points. FITLINE adds a least squares line, a line through the origin, or the mean of Y, over all points (LINE=TOTAL, the default) or per group (MEFFECT); the footnote gives each line’s intercept and slope. The points and lines are unweighted.

A variable takes its TYPE from its measurement level when none is given. A scale COLOR variable only colors the elements, so it is ignored. CATORDER sorts the categories of a variable by value (the default), label, weighted count or first case. PANEL repeats the chart for each combination of the panel categories. TITLE, SUBTITLE and CAPTION go above and below the chart (a \n inside becomes a space); VIEWNAME names it in the outline. X1 and Y TITLE name the axes, MAX sets the top of the axis. A case missing on a variable of the chart is left out; MISSING works as in GRAPH. With SPLIT FILE each group gets a chart.

Keywords that only change the look (CHARTLOOK, the LENGTH subcommands, EFFECT, SIZE, KEY=OFF, LEGEND=OFF, MIN, label, baseline, whisker, cap and line style settings, JITTER, SHOWEMPTY, X1INTERVAL and X1START, FORMAT) are accepted and named in one warning. REFLINE, SPIKE, FITLINE METHOD=LLR, FITLINE INTERVAL and SPIKE=ON cannot be drawn and give an error, as do X2 outside a scatterplot and a mix of elements other than those above.

Example

IGRAPH /X1=VAR(store) TYPE=CATEGORICAL /Y=VAR(basket) TYPE=SCALE /COLOR=VAR(daypart) /BAR (MEAN).

statscraft help IGRAPH prints the same text in the terminal. All commands

Statscraft 0.61.0, release v0.61.0

XGRAPH

Charts from one expression: summaries as bars or lines, clustered, stacked and paneled, population pyramids, binned histograms, dot plots and boxes.

Syntax

XGRAPH [CHART=] (y [+ y ...]) [> var | 1] [BY x [> var] [BY z [> var]]]
   [/BIN START=AUTO | n SIZE=AUTO | WIDTH(n) | COUNT(n)] [/DISPLAY DOT=ASYMMETRIC | SYMMETRIC | FLAT]
   [/DISTRIBUTION TYPE=NORMAL] [/COORDINATE SPLIT=NO | YES] [/ERRORBAR CI(level) | STDDEV(n) | SE(n)]
   [/MISSING USE=LISTWISE | VARIABLEWISE REPORT=NO | YES]
   [/PANEL COLVAR=varlist [COLOP=CROSS | NEST] ROWVAR=varlist [ROWOP=CROSS | NEST]]
   [/TEMPLATE FILE='file'] [/TITLES TITLE='line' ['line'] SUBTITLE='line' FOOTNOTE='line' ['line']].

y: var [function] [element], (var + var …) [function] [element], or [count function] [element].

x, z: var [c] or [s], $CASENUM [LABEL=var], or 1, the stand-in for the y variables.

function: COUNT PCT CUPCT CUFREQ (no variable); VALUE; MINIMUM MAXIMUM VALIDN SUM CUSUM MEAN STDDEV VARIANCE MEDIAN GMEDIAN MODE, PTILE(p), GPTILE(p), PLT PGT NLT NGT(x), PIN NIN(low, high).

element: BAR (the default), LINE, HISTOBAR, POINT, BOX. Square brackets are typed as shown, one keyword in each; names and keywords are written in full, each subcommand at most once.

BAR and LINE draw the function of y for every category of x. A variable after > on y stacks the bars; one after > on x clusters them; z gives the series when neither is there. Every further dimension (a second cluster, or z next to a stack or cluster) repeats the chart for each of its categories, as PANEL does. Several y variables, joined with +, need the 1 where they form the categories, the series or the stack. [VALUE] draws a bar for every case, the cases numbered on the axis that holds $CASENUM or named by its LABEL variable; a variable on the other axis gives a chart for each of its categories. [COLOR] and [PATTERN] after a stack or cluster variable are accepted and change nothing. GMEDIAN and GPTILE take each value as the midpoint of its interval and interpolate on the cumulative weights; a percentile below the first midpoint or above the last is missing.

COORDINATE SPLIT=YES turns a bar chart into a population pyramid: horizontal bars with a series for each category of z. HISTOBAR counts the cases in bins of a scale x and draws a histogram for each category of z, all with the same bins, which BIN sets (by default as FREQUENCIES makes them; COUNT(n) gives n bins from the start to the largest value).

DISTRIBUTION adds the normal curve of each histogram. POINT puts a dot for every case at its x value; DISPLAY stacks equal values up from 1 (ASYMMETRIC), around 0 (SYMMETRIC) or not at all (FLAT). BOX draws Tukey boxes of the y variable by x, side by side by the x cluster or z.

ERRORBAR adds bars to counts and percentages (CI: Jeffreys’ interval; SE and STDDEV: n times the binomial spread of the count), means, and medians (CI only). MISSING USE=LISTWISE leaves out a case missing on any y variable, VARIABLEWISE only from that variable; REPORT=YES keeps categories of missing values. TITLES lines may hold )DATE, )TIME and )CHART. TEMPLATE is accepted and ignored with a warning. With SPLIT FILE each group gets its charts.

Example

XGRAPH CHART=(spend [MEAN] [BAR]) BY region[c] > channel[c] BY season[c]
  /ERRORBAR SE(1) /TITLES TITLE='Spend by region'.

statscraft help XGRAPH prints the same text in the terminal. All commands

Statscraft 0.61.0, release v0.61.0

PPLOT

Probability plots: Q-Q or P-P plots of variables against a test distribution.

Syntax

PPLOT [VARIABLES=] varlist
   [/DISTRIBUTION=NORMAL[(a,b)] | EXPONENTIAL[(a)] | WEIBULL[(a,b)] | PARETO[(a,b)] |
    LNORMAL[(a,b)] | BETA[(a,b)] | GAMMA[(a,b)] | LOGISTIC[(a,b)] | LAPLACE[(a,b)] |
    UNIFORM[(a,b)] | HNORMAL[(a)] | CHI(df) | STUDENT(df)]
   [/FRACTION=BLOM | RANKIT | TUKEY | VW] [/TIES=MEAN | LOW | HIGH | BREAK]
   [/TYPE=Q-Q | P-P] [/PLOT=BOTH | NORMAL | DETRENDED] [/STANDARDIZE | /NOSTANDARDIZE]
   [/LN | /NOLOG] [/DIFF[=n]] [/SDIFF[=n]] [/PERIOD=n] [/TEMPLATE='file'] [/APPLY].

Parameters: NORMAL, LOGISTIC, LAPLACE location and scale; EXPONENTIAL rate; WEIBULL, LNORMAL scale and shape; PARETO threshold and shape; BETA two shapes; GAMMA shape and rate; UNIFORM minimum and maximum; HNORMAL scale (location 0). Without them they are estimated from the plotted values (moments; Weibull by least squares on the ranks; Pareto from the minimum and the mean log; half-normal by maximum likelihood) and listed in a table. Each variable is a series in case order: missing values are left out (user-missing ones kept under TSET MISSING=INCLUDE), LN logs it first (0 and below become missing), DIFF and SDIFF (over PERIOD cases, else TSET PERIOD, else the DATE period; with none SDIFF is left out) difference it, STANDARDIZE makes z-scores of the result. Ranks of tied values follow TIES (BREAK numbers the distinct values 1, 2, …); FRACTION turns rank r of n into a proportion p: BLOM (r-3/8)/(n+1/4), RANKIT (r-1/2)/n, TUKEY (r-1/3)/(n+1/3), VW r/(n+1).

Q-Q (the default) plots each value against the distribution’s quantile at p, P-P plots p against the distribution function at the value, both with the line y = x; the detrended plot shows observed minus expected, with the line y = 0. BOTH draws both plots. Values the distribution cannot take leave the variable out with a warning. Weights are not used.

APPLY repeats the previous PPLOT, or the model named in quotes (MOD_1, MOD_2, … in the order the session made them) (its distribution without the parameters, and its variables unless new ones are given); the subcommands given with it override. TEMPLATE is ignored; charts come as data.

Example

PPLOT VARIABLES=wait_min /DISTRIBUTION=GAMMA /TYPE=P-P /PLOT=NORMAL.

statscraft help PPLOT prints the same text in the terminal. All commands

Statscraft 0.61.0, release v0.61.0

NPPLOT

Another name for PPLOT.

Syntax

NPPLOT [VARIABLES=] varlist [/subcommands of PPLOT].

The same command as PPLOT, with the same subcommands and defaults.

Example

NPPLOT battery_hours /DISTRIBUTION=WEIBULL /FRACTION=VW.

statscraft help NPPLOT prints the same text in the terminal. All commands

Statscraft 0.61.0, release v0.61.0

ROC

ROC curve of test variables against a state, with the area under the curve.

Syntax

ROC testvars BY state(value)
   [/MISSING=EXCLUDE | INCLUDE]
   [/CRITERIA=[CUTOFF(INCLUDE | EXCLUDE)] [TESTPOS(LARGE | SMALL)] [CI(95)]
              [DISTRIBUTION(FREE | NEGEXPO)]]
   [/PLOT=CURVE[(REFERENCE)] | NONE] [/PRINT=[SE[(MODELQUALITY)]] [COORDINATES]].

The test variables are numeric; the state variable may be a string, and the value in parentheses is its positive state, every other valid state negative. Cases with a missing state or test value are left out of every curve (MISSING=INCLUDE keeps user-missing values); weights count cases. TESTPOS(SMALL) makes low test values point to the positive state. Each cutoff lies halfway between neighboring test values, plus one below the smallest and one above the largest; a value equal to a cutoff tests positive unless CUTOFF(EXCLUDE).

Tables: Case Processing Summary; Area Under the Curve, which counts every positive and negative pair (a tie as half) and with SE adds the nonparametric standard error (or the bi-negative exponential one under NEGEXPO when both groups are equally large), the two-sided test of area 0.5 and the CI interval; COORDINATES lists sensitivity and 1 - specificity at every cutoff. CURVE draws the curves in one chart, REFERENCE adds the diagonal; MODELQUALITY adds a bar chart of the lower bounds of the intervals.

A subcommand given twice counts once, the last, and a keyword that contradicts an earlier one of its subcommand overrides it; each is said in a warning. DMROC is another name for the command.

Example

ROC risk_score lab_index BY relapsed (1) /PLOT=CURVE(REFERENCE) /PRINT=SE COORDINATES.

statscraft help ROC prints the same text in the terminal. All commands

Statscraft 0.61.0, release v0.61.0

DMROC

Another name for ROC.

Syntax

DMROC testvars BY state(value) [/subcommands of ROC].

The same command as ROC, with the same subcommands and defaults.

Example

DMROC propensity BY bought (1) /PLOT=CURVE.

statscraft help DMROC prints the same text in the terminal. All commands

Statscraft 0.61.0, release v0.61.0

ROC ANALYSIS

ROC curves with paired or two-group comparisons of their areas, precision-recall curves and classifier metrics.

Syntax

ROC ANALYSIS testvars BY state(value)
   [/MISSING USERMISSING=EXCLUDE | INCLUDE]
   [/CRITERIA [CUTOFF=INCLUDE | EXCLUDE] [TESTPOS=LARGE | SMALL] [CI=95]
              [DISTRIBUTION=FREE | NEGEXPO]]
   [/DESIGN [PAIR=FALSE | TRUE] [GROUP=var]
            [SELECT=LEVEL(value value) | MIDPOINT | CUTPOINT(value)]]
   [/PLOT [CURVE=ROC[(REFERENCE)] [PR[(REFERENCE)]] | NONE] [PR_INTERPOLATE=TP | FP]
          [MODELQUALITY=FALSE | TRUE]]
   [/PRINT [SE=FALSE | TRUE] [COORDINATES=[ROC] [PR]] [CLASSIFIER=FALSE | TRUE]].

Every keyword may also be written KEY(value). Test variables are numeric; the state variable may be a string, its value in parentheses marks the positive cases and every other valid state is negative. A case takes part when its state, all test variables and the grouping variable are valid (USERMISSING=INCLUDE keeps user-missing values).

Weights are rounded to whole numbers and count cases; a weight of 0.5 or less, or a missing one, makes the case missing. Cutoffs, directions and areas as in ROC; when every test value lies strictly between 0 and 1 the outer cutoffs are 0 and 1.

Without DESIGN each test variable gets its own area. PAIR=TRUE compares every pair of two or more test variables measured on the same cases: the errors of the areas and of their differences follow DeLong’s method, and NEGEXPO does not apply. GROUP with SELECT compares two independent groups of cases for each test variable (PAIR is then ignored): LEVEL names the value of each group; MIDPOINT (halfway between the smallest and largest group value) and CUTPOINT split a numeric grouping variable into the cases at or above the point and those below it. NEGEXPO needs equally many positive and negative cases in both groups, else both groups use the nonparametric error.

Tables: Case Processing Summary; Area Under the ROC Curve (SE=TRUE adds the standard error, the test of area 0.5 and the CI interval); CLASSIFIER adds the Gini index 2 x area - 1 and the largest gap between sensitivity and 1 - specificity (Max K-S) with its cutoff; the paired or independent design adds a table of area differences with z tests and intervals; COORDINATES lists sensitivity and 1 - specificity (ROC) or precision and recall (PR) at every cutoff. CURVE draws ROC curves (the default), PR curves or none; with groups each test variable gets its own chart. PR curves are filled in between cutoffs one true positive (TP) or one false positive (FP) at a time; PR(REFERENCE) draws the share of positive cases. MODELQUALITY=TRUE adds a bar chart of the lower bounds of the area intervals.

Example

ROC ANALYSIS score_a score_b BY diseased (1) /DESIGN PAIR=TRUE /PRINT SE=TRUE CLASSIFIER=TRUE /PLOT CURVE=ROC(REFERENCE) PR.

statscraft help ROC ANALYSIS prints the same text in the terminal. All commands

Statscraft 0.61.0, release v0.61.0

SPCHART

Control charts (X-bar with R or s, individuals, p, np, c, u) and the process capability chart.

Syntax

SPCHART [/TITLE='line' ['line']] [/SUBTITLE='line'] [/FOOTNOTE='line' ['line']]
   /XR | /XS = var BY group | var var [var ...] [BY label] [(XBARONLY)]
   | /IR | /I = var [BY label]
   | /P | /NP = status BY group | COUNT(var) N(var | n) [BY label]
   | /C | /U = defects BY group | COUNT(var) N(var | n) [BY label]
   | /CPCHART = var BY group | var var [var ...] | var
   [/STATISTICS=keywords] [/RULES=[ALL] [UCL] [R2UPPER] [R4UPPER] [R8UPPER] [R8LOWER]
             [R4LOWER] [R2LOWER] [LCL] [TRUP] [TRDOWN] [ALTERNATING]] [/ID=var]
   [/CAPSIGMA=RBAR | SBAR | MRBAR | WITHIN] [/SPAN=2] [/CONFORM | /NONCONFORM=value]
   [/SIGMAS=3] [/MINSAMPLE=2] [/LSL=value] [/USL=value] [/TARGET=value]
   [/MISSING=[NOREPORT | REPORT] [EXCLUDE | INCLUDE]]
   [/NORMAL=CAPABILITY | PERFORMANCE | BOTH | NONE] [/REFERENCE=[SL] [SIGMAS] | NONE]
   [/TEMPLATE='file'].

One chart subcommand; XR may be left out. Each control chart is a line chart of the process with its center line and the control limits at SIGMAS sigmas (lower limits of ranges, standard deviations and counts stop at 0, a p chart’s upper one at 1, an np chart’s at the subgroup size); a series that is the same everywhere carries its value in its name. LSL and USL add fixed limit lines to the first chart. var BY group: cases are units, gathered into subgroups by the group variable in ascending order; var var …: each case is a subgroup, one unit per variable. XR and XS plot subgroup means with sigma from the mean of R/d2(n) or S/c4(n), then the ranges or standard deviations (left out with XBARONLY); subgroups below MINSAMPLE units are dropped. IR and I plot each value with sigma from the mean moving range over SPAN values over d2(SPAN); IR adds the moving ranges, missing for the first SPAN-1 points. P plots the share nonconforming against the pooled share, NP the number; CONFORM names the one good value of the status (any other value is a defect), NONCONFORM the one bad value. C plots defects per subgroup, U defects per unit. COUNT and N read counts and sizes from each case; a count above its size drops a p or np subgroup. Unequal sizes give each subgroup its own limits, with a warning for np and c. BY label only names the points, else they are numbered by case.

RULES (ALL when empty) checks the first chart: beyond a control limit, 2 of 3 past 2 sigma, 4 of 5 past 1 sigma, 8 on one side of the center, 6 rising or falling, 14 going up and down in turn; only the last point of a pattern counts. The Rule Violations table names the points by ID, else by the BY value. CPCHART draws a histogram with the normal curve of the mean and the capability sigma (NORMAL: PERFORMANCE uses the standard deviation, NONE none, BOTH draws the capability curve); LSL and USL are required, REFERENCE values go to the footnote.

STATISTICS (XR, XS, IR, I and CPCHART): CP CPL CPU K CPK CR CPM CZL CZU CZMIN CZMAX CZOUT CZLOUT CZUOUT with the capability sigma, PP PPL PPU PPK PR PPM PZL PZU PZMIN PZMAX PZOUT PZLOUT PZUOUT with the standard deviation of all values, N MEAN STDDEV CAPSIGMA LSL USL TARGET, and AZOUT AZLOUT AZUOUT, the observed percentages at or past the limits. Keywords that need LSL and USL, or TARGET between them, are left out with a warning. CAPSIGMA: RBAR (XR), SBAR (XS) or WITHIN for subgroups, MRBAR for single values. CPCHART without STATISTICS lists its indices in a table. MISSING: REPORT keeps subgroups for missing BY values, INCLUDE counts user-missing process values. Weights count only for units, whole positive ones; each unit of an individuals chart is repeated by its weight. A chart has 2 to 3000 points. TEMPLATE is ignored; charts come as data.

Example

SPCHART /XR=fill_ml BY batch /RULES=ALL /STATISTICS=CP CPK PP PPK /LSL=495 /USL=505.

statscraft help SPCHART prints the same text in the terminal. All commands

Statscraft 0.61.0, release v0.61.0

KM

Kaplan-Meier survival estimates by factor level and stratum, with tests that compare the levels.

Syntax

KM time [BY factor] /STATUS=var [EVENT](values) [LOST(values)]
   [/STRATA=var] [/ID=var] [/PLOT=[SURVIVAL] [LOGSURV] [HAZARD] [OMS]]
   [/PRINT=[TABLE] [MEAN] [NONE]] [/PERCENTILES=[(]values[)]]
   [/TEST=[LOGRANK] [BRESLOW] [TARONE]] [/COMPARE=[OVERALL | PAIRWISE] [POOLED | STRATA]]
   [/TREND[=(weights)]] [/SAVE=[SURVIVAL[(name)]] [HAZARD[(name)]] [SE[(name)]] [CUMEVENT[(name)]]].

K-M is another name. A case whose status is one of the EVENT values (single values or a THRU b, quoted for a string status) had the event at its time; any other status counts as censored, and LOST values are counted apart in the tables though they are censored too. Cases with a missing time, status, factor or stratum, or a negative time, are left out; weights count cases. Each factor level within each stratum gets its own curve.

Tables: Case Processing Summary; a Survival Table per curve, a row per case with the estimate and its Greenwood standard error at each event time, the events so far and the cases still at risk (ID labels the rows); Means and Medians, the mean being the area under the curve up to the longest time; Percentiles (25, 50 and 75 when no values are given), where the p% value is the first event time at which the estimate is p/100 or lower. PRINT names what to show: TABLE, MEAN or NONE.

With a factor, the log rank test (or TEST: Breslow, weighted by the cases at risk, and Tarone-Ware, by their square root) compares the levels: all at once or each pair (PAIRWISE), pooled over the strata or within each (STRATA). TREND tests a linear trend over the levels in ascending order with one degree of freedom, with the given weights or evenly spaced ones centered on 0. PLOT draws, for each stratum, the step curves of the levels with censored times marked: SURVIVAL, LOGSURV (its log), HAZARD (minus its log, the cumulative hazard) and OMS (one minus it). SAVE adds the estimate, the cumulative hazard, the standard error and the events up to each case’s time; the default names are SUR_n, HAZ_n, SE_n and CUM_n.

Example

KM weeks BY plan /STATUS=outcome EVENT(1) LOST(2) /STRATA=region /TEST=LOGRANK BRESLOW /COMPARE=PAIRWISE /PLOT=SURVIVAL.

statscraft help KM prints the same text in the terminal. All commands

Statscraft 0.61.0, release v0.61.0

K-M

Another name for KM.

Syntax

K-M time [BY factor] /STATUS=var [EVENT](values) [/subcommands of KM].

The same command as KM, with the same subcommands and defaults.

Example

K-M days_to_repair /STATUS=fixed(1).

statscraft help K-M prints the same text in the terminal. All commands

Statscraft 0.61.0, release v0.61.0

SURVIVAL

Actuarial life tables over fixed time intervals, with the Wilcoxon (Gehan) comparison of groups.

Syntax

SURVIVAL [TABLES=] times [BY controls(min, max) ...] [BY controls(min, max) ...]
   /INTERVAL=THRU end BY width [THRU end BY width ...]
   /STATUS=var(min[, max]) [FOR times] [/STATUS=...]
   [/PLOTS[(ALL | SURVIVAL | LOGSURV | HAZARD | DENSITY | OMS ...)][=times BY controls BY controls]]
   [/PRINT=TABLE | NOTABLE] [/COMPARE[=times BY controls BY controls]]
   [/CALCULATE=[EXACT | CONDITIONAL | APPROXIMATE] [PAIRWISE] [COMPARE]]
   [/MISSING=[GROUPWISE | LISTWISE] [INCLUDE]] [/WRITE[=NONE | TABLES | BOTH]].

Intervals start at 0; each THRU … BY period continues where the last one ended, and a period that the width does not divide evenly is stretched to the next whole interval.

One more interval, open at the top, holds the longer times. A time falls into the interval whose start it reaches. A case whose status lies in the range had the event; other cases are censored and count as half exposed in their interval. STATUS without FOR serves every time variable that no other STATUS names. Each control’s values are truncated to whole numbers and kept inside its range; first order controls each split the cases on their own, a second BY splits every one of those again.

The life table shows, per interval with cases entering: those entering, withdrawing, exposed to risk and having the event, the proportions ending and surviving, the cumulative survival at the interval’s end with its standard error, the density and the hazard with theirs (none for the open interval). Median Survival Times interpolates inside the interval where the cumulative survival passes 0.5, or shows the start of the last interval cases entered with a plus sign. Weights count cases, so counts per interval may be entered as weighted records. Negative times are missing.

COMPARE tests whether the groups of each first order control share one survival curve, with Gehan’s scores (a tie between an event and a censored time ranks the event first); CALCULATE PAIRWISE adds each pair of values, APPROXIMATE scores the interval of each time instead of the time, COMPARE gives the comparisons only. MISSING=GROUPWISE leaves a case out only of the tables whose variables it misses; LISTWISE leaves out a case missing on any TABLES variable (a missing status only affects its own time variable); INCLUDE keeps user-missing values. PLOTS draws, per time variable, first order control and second order value, the survival function, its log, the hazard, the density or one minus survival, the groups as lines. WRITE puts the life tables in the file of the PROCEDURE OUTPUT before the command, as fixed-column records: with TABLES, a type 30 and a type 31 record for each line of a table and a type 40 at its end; with BOTH also a type 10 record (the survival variable) and a type 20 record for each control variable of the table.

Example

SURVIVAL TABLES=weeks BY plan(1,3) /INTERVAL=THRU 30 BY 5 /STATUS=outcome(1) /COMPARE /CALCULATE=PAIRWISE /PLOTS(SURVIVAL,HAZARD).

statscraft help SURVIVAL prints the same text in the terminal. All commands

Statscraft 0.61.0, release v0.61.0

REPORT

Case listings and summary statistics by break groups, laid out as a report.

Syntax

REPORT [FORMAT=[MANUAL | AUTOMATIC] [NOLIST | LIST[(n)]] [ALIGN(LEFT | CENTER | RIGHT)] [TSPACE(1)]
        [CHDSPACE(1)] [FTSPACE(1)] [SUMSPACE(1)] [COLSPACE(4)] [BRKSPACE(n | -1)] [LENGTH(t,b)]
        [MARGINS(l,r)] [CHALIGN(TOP | BOTTOM)] [UNDERSCORE(ON | OFF)] [PAGE1(1)] [MISSING '.']
        [ONEBREAKCOLUMN ON | OFF] [INDENT(2)] [CHWRAP ON | OFF] [PREVIEW ON | OFF]]
   [/OUTFILE='path'] [/STRING=name (var [(width)] [(BLANK)] 'literal' ...) ...]
   /VARIABLES=var [(VALUE | LABEL | DUMMY)] [+ var ...] ['heading' ...] [(width)]
      [(OFFSET(n | CENTER))] [(LEFT | CENTER | RIGHT)] ...
   [/MISSING=VAR | NONE | LIST[([varlist] [n])]] [/TITLE=[LEFT | CENTER | RIGHT] 'line' ...]
   [/FOOTNOTE=[LEFT | CENTER | RIGHT] 'line' ...]
   [/BREAK=varlist | (TOTAL) ['heading' ...] [(width)] [(VALUE | LABEL)] [(TOTAL | NOTOTAL)]
      [(SKIP(1))] [(PAGE)] [(OFFSET(n | CENTER))] [(UNDERSCORE[(varlist)])] [(LEFT | CENTER | RIGHT)]
      [(NAME | NONAME)] [/SUMMARY=function ... ['title'] [(break column)] [SKIP(n)] | PREVIOUS[(n)]] ...] ...

functions: VALIDN SUM MIN MAX MEAN STDDEV (SD, STDEV) VARIANCE KURTOSIS SKEWNESS MEDIAN(min,max) MODE(min,max) PGT(n) PLT(n) PIN(min,max) FREQUENCY(min,max) PERCENT(min,max), each with an optional (var [(format | PLAIN)] [(decimals)] …); composite functions DIVIDE(a b [factor]) MULTIPLY PCT(a b) SUBTRACT(a b) ADD GREAT LEAST AVERAGE of aggregates such as SUM(var) and numbers, with an optional (column [(format)] [(decimals)]).

The report is a table: a column for each BREAK (with ONEBREAKCOLUMN ON one for all, indented by INDENT), then one for each report column, headed by its heading or the variable label or name. LIST lists the cases, each value in its print format or with LABEL as its value label; a stacked column lists each of its variables on a line of its own. A break group starts when a value of its BREAK or an earlier one changes (sort the cases first): its values head it, and its SUMMARY lines follow with their title (by default the function’s) in the break column. The statistics use the valid values and the weight; MISSING=NONE counts user-missing values as valid, and MISSING=LIST leaves out the cases missing on n of the variables. MEDIAN, MODE, FREQUENCY and PERCENT count the whole numbers of the range, cutting decimals off.

TOTAL on the first BREAK repeats its first SUMMARY for all cases at the end, under Grand Total. Each function has its own default format. TITLE and FOOTNOTE lines (by default the text of the TITLE command) show above and below the report; )PAGE, )DATE and )var in them give the page number, the date and the value label of the first case. OUTFILE writes the report as text, with the column widths, spacing and alignment, instead of showing it; a later REPORT of the same session appends to the file. The report is one page, so LENGTH, PAGE and PREVIEW change nothing.

Example

SORT CASES BY region.
REPORT FORMAT=LIST /VARIABLES=shop (LABEL) visitors 'Weekly' 'visitors'
  /BREAK=region 'Region' (LABEL) /SUMMARY=VALIDN(shop) MEAN(visitors).

statscraft help REPORT prints the same text in the terminal. All commands

Statscraft 0.61.0, release v0.61.0

MATRIX

Run a program in the matrix language, up to END MATRIX.

Syntax

MATRIX.
  COMPUTE m = expr | m(rows, cols) = expr.
  CALL EIGEN(m, vectors, values) | SETDIAG(m, v) | SVD(m, u, q, v).
  PRINT [m] [/FORMAT=format] [/TITLE='text'] [/SPACE=n | NEWPAGE]
        [/RLABELS=labels | /RNAMES=vector] [/CLABELS=labels | /CNAMES=vector].
  DO IF expr. ... [ELSE IF expr. ...] [ELSE. ...] END IF.
  LOOP [i = first TO last [BY step]] [IF expr]. ... [BREAK.] ... END LOOP [IF expr].
  READ m [/FILE=file] /FIELD=c1 TO c2 [BY w] [/SIZE=expr] [/MODE=RECTANGULAR | SYMMETRIC]
        [/REREAD] [/FORMAT=format].
  WRITE m [/OUTFILE=file] /FIELD=c1 TO c2 [BY w] [/MODE=RECTANGULAR | TRIANGULAR] [/HOLD]
        [/FORMAT=format].
  GET m [/FILE=file | *] [/VARIABLES=varlist] [/NAMES=name] [/MISSING=ACCEPT | OMIT | value]
        [/SYSMIS=OMIT | value].
  SAVE m [/OUTFILE=file | *] [/VARIABLES=names] [/NAMES=vector] [/STRINGS=names].
  MGET [/FILE=file | *] [/TYPE=COV CORR MEAN STDDEV N COUNT].
  MSAVE m /TYPE=COV | CORR | MEAN | STDDEV | N | COUNT [/OUTFILE=file] [/VARIABLES=names]
        [/SNAMES=names] [/SPLIT=vector] [/FNAMES=names] [/FACTOR=vector].
  DISPLAY [DICTIONARY] [STATUS].
  RELEASE m [, m ...].

END MATRIX.

Matrices: {1, 2; 3, 4} (commas between elements, semicolons between rows; the parts may be matrices), a:b and a:b:step for whole numbers, m(i, j) and v(i) with vectors of positions or : for all.

Operators from the tightest: unary -, :, ** (matrix power) and &**, * (matrix product), / &* and &/ (elementwise), + -, < <= > >= = <> (or LT LE GT GE EQ NE), NOT, AND, OR and XOR; a scalar goes with any matrix. PRINT, WRITE, SAVE and MSAVE take a name, a call, a matrix in braces or a power of one; other expressions go in parentheses, as (A+B). In the expression of a subcommand a slash starts the next subcommand, so a division goes in brackets.

Functions: ABS ALL ANY ARSIN ARTAN BLOCK CHOL CMAX CMIN COS CSSQ CSUM DESIGN DET DIAG EOF EVAL EXP GINV GRADE GSCH IDENT INV KRONEKER LG10 LN MAGIC MAKE MDIAG MMAX MMIN MOD MSSQ MSUM NCOL NROW RANK RESHAPE RMAX RMIN RND RNKORDER RSSQ RSUM SIN SOLVE SQRT SSCP SVAL SWEEP T (TRANSPOS) TRACE TRUNC; UNIFORM(rows, cols) and NORMAL(rows, cols) give random matrices, UNIFORM(max) and NORMAL(sd) random elements; CDFNORM CHICDF FCDF TCDF PROBIT and the families CDF.x, IDF.x, PDF.x, NCDF.x, NPDF.x, SIG.x and RV.x work element by element, a scalar argument going with any matrix.

PRINT gives a table; without FORMAT the numbers share one format and are divided by a power of 10, named in the caption, when they are very large or small. A string element holds up to 8 bytes and prints with an A format. Every loop, also one with an index, stops after SET MXLOOPS iterations (default 40) with a warning. The first READ, WRITE, SAVE and MSAVE name their file; later ones use the last one named. SAVE, MSAVE and WRITE write their files at END MATRIX; SAVE /OUTFILE=* replaces the active dataset then. An error stops the program at its statement, and nothing is saved.

Example

MATRIX.
COMPUTE A = {4, 2; 2, 3}.
CALL EIGEN(A, V, E).
PRINT E /TITLE='Eigenvalues'.
PRINT INV(A) /FORMAT=F8.3.
END MATRIX.

statscraft help MATRIX prints the same text in the terminal. All commands

Statscraft 0.61.0, release v0.61.0

Time series

命令功能 {#what-it-does}
TSETSettings shared by the time series procedures.
TSHOWList the time series settings.
VERIFYCheck the DATE variables and report the USE and PREDICT periods.
CREATENew series from functions of existing series: lags, differences, smoothers, FFT.
RMVCopies of series with the missing values filled in by interpolation, a mean, a median or a trend.
ACFAutocorrelations of time series, with standard errors, Box-Ljung tests and charts.
PACFPartial autocorrelations of time series, with standard errors and charts.
CCFCross-correlations of pairs of time series, with standard errors and charts.
SEASONSeasonal decomposition by ratios (or differences) to a moving average.
PREDICTSet the forecast period of EXSMOOTH and ARIMA.
EXSMOOTHExponential smoothing with or without trend and season, with fitted values and forecasts.
ARIMASeasonal ARIMA models with regressors by exact maximum likelihood, with forecasts.
AREGRegression whose errors follow a first-order autoregressive process.
SPECTRAPeriodogram, smoothed spectral density and cross-spectra of series.
2SLSTwo-stage least squares for equations with endogenous predictors.
TSMODELExponential smoothing and ARIMA models of series, picked by hand or by the expert modeler, with forecasts.
TSAPPLYForecasts from time series models that TSMODEL saved, as they are or estimated again.
TSPLOTChart of time series over the cases, as chart data.
CASEPLOTChart of time series with the cases down the vertical axis, as chart data.
FITGoodness-of-fit statistics of residual series from time series models.

All commands

Statscraft 0.61.0, release v0.61.0

TSET

Settings shared by the time series procedures.

Syntax

TSET [PRINT=BRIEF | DEFAULT | DETAILED] [NEWVAR=CURRENT | NONE | ALL] [MXAUTO=16]
     [MXCROSS=7] [MXNEWVARS=60] [MXPREDICT=60] [MISSING=EXCLUDE | INCLUDE] [CIN=95]
     [TOLER=0.0001] [CNVERGE=0.001] [ACFSE=IND | MA] [PERIOD=n] [ID=variable]
     [CONSTANT | NOCONSTANT] [DEFAULT].

The values shown are the starting ones. Slashes and equals signs are optional, and DEFAULT as a value puts that one setting back; DEFAULT alone puts back all of them. A setting holds for the rest of the session, until TSET changes it; a subcommand of a procedure that does the same job wins for that procedure. Who reads what: ACF, PACF and CCF take MXAUTO, MXCROSS, ACFSE, PERIOD and MISSING; SEASON takes PERIOD, PRINT, NEWVAR, MXNEWVARS and MISSING; PPLOT takes PERIOD and MISSING; CREATE takes PERIOD (for SDIFF) and MISSING; CURVEFIT takes NEWVAR, MXNEWVARS, CIN, TOLER, CONSTANT, ID and MISSING; WLS takes NEWVAR, MXNEWVARS, PRINT and CONSTANT. NEWVAR: CURRENT saves the new variables of a procedure under names numbered from 1, replacing variables of those names; ALL saves them under the next free numbers; NONE saves nothing unless the procedure’s SAVE asks. A procedure that would make more than MXNEWVARS variables saves none, with a warning. PERIOD wins over the period that DATE variables give. MXPREDICT and CNVERGE are kept and shown by TSHOW; no procedure reads them. NEWVARS is taken as NEWVAR.

Example

TSET PERIOD=4 MXAUTO=12 NEWVAR=ALL.

statscraft help TSET prints the same text in the terminal. All commands

Statscraft 0.61.0, release v0.61.0

TSHOW

List the time series settings.

Syntax

TSHOW.

A table with every TSET setting, the period the DATE variables of the active dataset give (if any), and the period the procedures use when they are not told one.

Example

TSHOW.

statscraft help TSHOW prints the same text in the terminal. All commands

Statscraft 0.61.0, release v0.61.0

VERIFY

Check the DATE variables and report the USE and PREDICT periods.

Syntax

VERIFY [[VARIABLES=]series].

A table with the first and last case of the file and of the USE and PREDICT periods, by case number and by DATE_ text, then a table of the date variables: how many values are missing or out of range, and a flag with the first case where a variable is not nested in the next higher one, begins or ends a cycle off its usual value, or steps by more than it should.

With a numeric series, a third table gives its values at those cases and its missing count (user-missing values count as missing unless TSET MISSING=INCLUDE).

Run it after SELECT IF, SORT CASES or AGGREGATE have changed the file, before a time series procedure.

Example

DATE YEAR 2018 MONTH.
VERIFY sales.

statscraft help VERIFY prints the same text in the terminal. All commands

Statscraft 0.61.0, release v0.61.0

CREATE

New series from functions of existing series: lags, differences, smoothers, FFT.

Syntax

CREATE new names = function(series [, numbers]) [/new names = function(...) ...].

function: CSUM(series) running total; DIFF(series, order) differences; SDIFF(series, order [, period]) differences over a period; LAG(series, order [, order]) and LEAD(series, order [, order]) shifted copies, one per order of the range; MA(series, span [, minimum]) centered moving average; RMED(series, span [, minimum]) centered running median; PMA(series, span) mean of the span cases before; T4253H(series) compound smoother; FFT(series) real and imaginary parts; IFFT(real, imaginary) the series back.

Commas or blanks separate the items in parentheses; v1 TO v4 names numbered new series. A function makes one series per source (LAG and LEAD: per source and order, sources outer; FFT two per source; IFFT one per pair), and the names on the left must match that count.

An existing variable of the same name is replaced; a later equation may use a series an earlier one made. A value missing (user-missing too, unless TSET MISSING=INCLUDE) gives a missing result where it is used; MA, RMED and PMA restart after it. An even span is centered by averaging two neighbouring spans. Near the ends MA and RMED shrink the span symmetrically down to the minimum (of the same parity, raised by 1 otherwise; 1 is always allowed). SDIFF without a period uses TSET PERIOD, then the DATE period. T4253H, FFT and IFFT need a series without gaps inside it; FFT pads an odd length with a 0 and gives n/2 cases (the first case’s imaginary part holds the highest frequency’s cosine term), IFFT twice as many as it reads. With SPLIT FILE each group is a series of its own; cases a filter leaves out keep their value (system-missing in a new series). A table lists every new series with its first and last valid case, its number of valid values and its function.

Example

CREATE sales_lag1 TO sales_lag3 = LAG(sales, 1, 3) /trend = MA(sales, 6, 2).

statscraft help CREATE prints the same text in the terminal. All commands

Statscraft 0.61.0, release v0.61.0

RMV

Copies of series with the missing values filled in by interpolation, a mean, a median or a trend.

Syntax

RMV new names = function(series) [/new names = function(...) ...].

function: LINT(series); MEAN(series [, span]); MEDIAN(series [, span]); SMEAN(series); TREND(series). span is a whole number of 1 or more, or ALL.

One new variable per series, in order, so the names on the left must match the count of series; v1 TO v4 names numbered variables. A new name that exists is replaced, also when it is the series itself. Valid values are copied. LINT draws a line between the nearest valid values before and after a gap, and leaves a gap at either end alone. MEAN and MEDIAN use the span nearest valid values on each side (2 without a span) and leave the gap alone when a side has fewer; ALL uses every valid value, as SMEAN does with the mean.

TREND fits a line to the valid values against the case position and uses it. An estimate never rests on another estimate. A user-missing value is missing unless TSET MISSING=INCLUDE.

With SPLIT FILE each group is a series of its own; USE is not used. A table lists each new variable with the number of values replaced, its first and last valid case, its number of valid values and its function.

Example

RMV tidy_load = LINT(hourly_load) /tidy_temp = MEDIAN(temp, 3).

statscraft help RMV prints the same text in the terminal. All commands

Statscraft 0.61.0, release v0.61.0

ACF

Autocorrelations of time series, with standard errors, Box-Ljung tests and charts.

Syntax

ACF [VARIABLES=] series [/DIFF=n] [/SDIFF=n] [/PERIOD=n] [/LN | /NOLOG] [/SEASONAL]
    [/MXAUTO=n] [/SERROR=IND | MA] [/PACF] [/APPLY].

Before the correlations each series may be logged (LN; a series with a value not above 0 is skipped), differenced DIFF times (DIFF alone: once) and then differenced over the period SDIFF times. The period comes from PERIOD (at least 2), else TSET PERIOD, else the DATE variables; without one SDIFF and SEASONAL are left out with a warning. MXAUTO (else TSET MXAUTO, else 16) is the highest lag, at most the number of values less one; SEASONAL shows only the lags that are multiples of the period. A missing value (user-missing too, unless TSET MISSING=INCLUDE) drops the products it is part of; the mean and the counts use the valid values. Each series gets a table: autocorrelation r_k, its standard error, and the Box-Ljung statistic of lags 1 to k with k df and its significance. IND (the default, or TSET ACFSE) takes the standard error of white noise, sqrt((n - k) / (n (n + 2))); MA takes Bartlett’s sqrt((1 + 2 (r_1^2 + … + r_(k-1)^2)) / n). PACF adds the partial autocorrelations, with standard error 1 / sqrt(n). A chart per series shows the coefficients with limits at two standard errors. APPLY repeats the previous ACF, or the model named in quotes (MOD_1, MOD_2, … in the order the session made them), with the subcommands given now replacing its own.

DIFFERENCE is another name for DIFF. Case weights are not used.

Example

ACF VARIABLES=daily_orders /DIFF /MXAUTO=21 /PACF.

statscraft help ACF prints the same text in the terminal. All commands

Statscraft 0.61.0, release v0.61.0

PACF

Partial autocorrelations of time series, with standard errors and charts.

Syntax

PACF [VARIABLES=] series [/DIFF=n] [/SDIFF=n] [/PERIOD=n] [/LN | /NOLOG] [/SEASONAL]
     [/MXAUTO=n] [/APPLY].

The series are prepared and the lags chosen as for ACF. The partial autocorrelations come from the autocorrelations by the Durbin-Levinson recursion; each has the standard error 1 / sqrt(n), n the number of valid values. A table and a chart (limits at two standard errors) per series. APPLY repeats the previous PACF, or the model named in quotes (MOD_1, MOD_2, … in the order the session made them).

Example

PACF river_level /SDIFF /PERIOD=7 /MXAUTO=28.

statscraft help PACF prints the same text in the terminal. All commands

Statscraft 0.61.0, release v0.61.0

CCF

Cross-correlations of pairs of time series, with standard errors and charts.

Syntax

CCF [VARIABLES=] series [WITH series] [/DIFF=n] [/SDIFF=n] [/PERIOD=n] [/LN | /NOLOG]
    [/SEASONAL] [/MXCROSS=n] [/APPLY].

Without WITH every series is paired with each one after it; with WITH each series before it is paired with each one after it. Both series of a pair are prepared as in ACF. At lag k the correlation is of x at time t with y at time t + k, so a positive lag means the first series leads; the sums use the cases where both are valid, divided by the root of the two sums of squares about their means. Lags run from -MXCROSS to MXCROSS (else TSET MXCROSS, else 7), at most the series length less one. The standard error is 1 / sqrt(m), m the number of valid pairs at that lag. A table and a chart (limits at two standard errors) per pair. APPLY repeats the previous CCF, or the model named in quotes (MOD_1, MOD_2, … in the order the session made them).

Example

CCF ad_spend WITH weekly_sales /DIFF /MXCROSS=10.

statscraft help CCF prints the same text in the terminal. All commands

Statscraft 0.61.0, release v0.61.0

SEASON

Seasonal decomposition by ratios (or differences) to a moving average.

Syntax

SEASON [VARIABLES=] series [/MODEL=MULTIPLICATIVE | ADDITIVE] [/MA=EQUAL | CENTERED]
       [/PERIOD=n] [/APPLY].

The period comes from PERIOD, else TSET PERIOD, else the DATE variables; the series needs at least four full periods and no missing value. A moving average over one period gives the trend: for an even period CENTERED (the default) spans period + 1 cases with half weight at both ends; EQUAL weighs the period cases equally, from period/2 cases before a case to period/2 - 1 after it. An odd period always uses EQUAL. The multiplicative model divides the series by it (times 100), the additive one subtracts it. For each position in the period the mean of these values without the largest and the smallest is the raw factor; the factors are scaled to average 100 (multiplicative) or centered on 0 (additive). The adjusted series SAS is the series divided by (or less) the factor, the trend-cycle STC a 1-2-3-2-1 weighted average of SAS (3-term at the second and next-to-last case, extrapolated at the ends) and the irregular part ERR SAS over (or less) STC. Tables: the model, the cases with every component (left out under TSET PRINT=BRIEF) and the seasonal factors. TSET NEWVAR saves ERR_n, SAS_n, SAF_n and STC_n per series; saved multiplicative factors are ratios, so SAS = series / SAF.

APPLY repeats the previous SEASON, or the model named in quotes (MOD_1, MOD_2, … in the order the session made them).

Example

SEASON VARIABLES=heating_kwh /MODEL=ADDITIVE /PERIOD=12.

statscraft help SEASON prints the same text in the terminal. All commands

Statscraft 0.61.0, release v0.61.0

PREDICT

Set the forecast period of EXSMOOTH and ARIMA.

Syntax

PREDICT [start] [THRU [end]].

Start and end are case numbers, or dates written with DATE keywords and values; END means the last case. Without a start the period begins right after the USE range (or the file); a start later than that is moved back to it. Without an end it runs to the last case of the file, or covers just its start when that lies past the file. EXSMOOTH and ARIMA estimate on the USE range, give one-step fitted values up to the case before the start and forecasts from there on, adding cases when the period runs past the end of the file (at most TSET MXPREDICT, default 60). Added cases are missing on every variable except the new ones and the DATE variables. Residuals are missing in the forecast period. DATE turns PREDICT off; it stays in force until the next PREDICT.

Example

PREDICT THRU YEAR 2026 MONTH 12.

statscraft help PREDICT prints the same text in the terminal. All commands

Statscraft 0.61.0, release v0.61.0

EXSMOOTH

Exponential smoothing with or without trend and season, with fitted values and forecasts.

Syntax

EXSMOOTH [VARIABLES=] series [/MODEL=NN | NA | NM | LN | LA | LM | EN | EA | EM | DN | DA | DM]
         [/PERIOD=n] [/SEASFACT=(factors) | variable]
         [/ALPHA=value | GRID[(start end step)]] [/GAMMA=...] [/DELTA=...] [/PHI=...]
         [/INITIAL=CALCULATE | (start trend)] [/APPLY].

The first letter of the model is the trend (N none, L linear, E exponential, D damped), the second the season (N none, A additive, M multiplicative); SINGLE means NN, HOLT LN and WINTERS LM. ALPHA smooths the level, GAMMA the trend (not in NN, NA, NM, DA, DM), DELTA the season and PHI damps the trend; each defaults to 0.1, a parameter the model does not use is ignored. ALPHA, GAMMA and DELTA lie from 0 to 1, PHI above 0 and below 1. GRID tries every value from start to end by step (defaults 0 to 1 by 0.1 for ALPHA, by 0.2 for GAMMA and DELTA, 0.1 to 0.9 by 0.2 for PHI); every combination is fitted and the one with the smallest sum of squared one-step errors is kept. The output lists the ten smallest (all of them under TSET PRINT=DETAILED). Start values come from the published formulas: means of the first and last complete periods, initial seasonal factors from SEASON’s method unless SEASFACT gives them (a list as long as the period, or a variable such as a saved SAF_n whose first values are read). INITIAL gives the start level and trend instead. A seasonal model needs a period (PERIOD, TSET PERIOD or DATE) and four full periods; the multiplicative and exponential models need values above 0. The series may not have missing values inside the USE range. TSET NEWVAR saves FIT_n (the one-step forecast) and ERR_n per series; with PREDICT, FIT_n holds the forecasts. APPLY repeats the previous EXSMOOTH, or the model named in quotes (MOD_1, MOD_2, … in the order the session made them) with the subcommands given now replacing its own; SEASFACT is not carried over.

Example

EXSMOOTH VARIABLES=room_nights /MODEL=DA /PERIOD=7 /PHI=GRID /DELTA=0.25.

statscraft help EXSMOOTH prints the same text in the terminal. All commands

Statscraft 0.61.0, release v0.61.0

ARIMA

Seasonal ARIMA models with regressors by exact maximum likelihood, with forecasts.

Syntax

ARIMA [VARIABLES=] series [WITH regressors]
      [/MODEL=[(p,d,q)[(sp,sd,sq)[period]]] [CONSTANT | NOCONSTANT] [NOLOG | LG10 | LN]]
      [/P=n | (lags)] [/D=n] [/Q=n | (lags)] [/SP=...] [/SD=n] [/SQ=...]
      [/AR=values] [/MA=values] [/SAR=values] [/SMA=values] [/REG=values] [/CON=value]
      [/MXITER=10] [/MXLAMB=1E9] [/SSQPCT=0.001] [/PAREPS=0.001] [/CINPCT=95]
      [/FORECAST=EXACT | CLS | AUTOINIT] [/APPLY [SPECIFICATIONS | INITIAL | FIT]].

The model is phi(B) PHI(B^s) (w_t - mu) = theta(B) THETA(B^s) a_t, w_t the series less the regressors times their coefficients, differenced d times and over the period sd times; the polynomials are 1 - c_1 B - …, so a positive MA coefficient means a negative weight on the past error. P, Q, SP and SQ name the lags to fit (n for 1 to n, a list in parentheses for those lags only) and win over MODEL. LOG is LG10; logs need values above 0. CONSTANT and the confidence level default to TSET. The estimates maximize the exact Gaussian likelihood (a Kalman filter that also takes missing values inside the series) by Levenberg-Marquardt steps on numerical derivatives. It stops after MXITER steps, when no estimate changes by PAREPS (default TSET CNVERGE), when the adjusted sum of squares changes by less than SSQPCT percent, or when the Marquardt constant passes MXLAMB.

MXITER=0 takes the initial values as final. AR, MA, SAR, SMA, REG and CON give initial values in the order of the lags. Output: the iteration history (TSET PRINT=BRIEF leaves it out, DETAILED adds the estimates of each step), the estimates with standard errors, t and approximate significance, the residual variance and standard error, the log-likelihood, AIC and SBC, and the covariance and correlation of the estimates. TSET NEWVAR saves FIT_n, ERR_n, LCL_n, UCL_n and SEP_n: one-step fitted values (EXACT: from the Kalman filter; CLS: past errors 0 and missing past values at the mean of the differenced series; AUTOINIT: the first values of the series as their own fits), the residuals on the log scale, the prediction limits and standard errors. Fits, limits and standard errors are taken back from logs. With PREDICT the fit continues as forecasts; with regressors only where they are valid, and the file is not extended.

APPLY repeats the previous ARIMA, or the model named in quotes (MOD_1, MOD_2, … in the order the session made them) with the subcommands given now replacing its own; INITIAL starts from its estimates, FIT uses them without estimation.

Example

ARIMA daily_calls WITH promo /MODEL=(1,0,1)(0,1,1) 7 NOCONSTANT /FORECAST=EXACT.

statscraft help ARIMA prints the same text in the terminal. All commands

Statscraft 0.61.0, release v0.61.0

AREG

Regression whose errors follow a first-order autoregressive process.

Syntax

AREG [VARIABLES=] series WITH regressors
     [/METHOD=PW | CO | ML] [/CONSTANT | /NOCONSTANT] [/RHO=0] [/MXITER=10]
     [/APPLY [SPECIFICATIONS | INITIAL | FIT]].

The errors of y = a + b x are taken to follow u_t = rho u_(t-1) + e_t. PW (the default, Prais-Winsten) and CO (Cochrane-Orcutt) alternate two steps: least squares on the quasi-differences y_t - rho y_(t-1), then a new rho from the lag-one products of the residuals. CO drops the first case; PW keeps it, scaled by sqrt(1 - rho^2). RHO is the start (above -1, below 1). The loop ends when no estimate moves by TSET CNVERGE or after MXITER rounds. Both take missing values at the ends of the USE range only. ML fits the same model by exact maximum likelihood (the ARIMA engine with one autoregressive term), missing values allowed anywhere. CONSTANT defaults to TSET.

Output: per iteration rho, its standard error, Durbin-Watson and the mean square error (TSET PRINT=DETAILED adds the coefficients, BRIEF keeps only the final estimates), the R square of the transformed regression at the start and the end, an ANOVA table, and the estimates with t tests; ML shows what ARIMA shows. TSET NEWVAR saves FIT_n, ERR_n, LCL_n, UCL_n and SEP_n; after the series, PREDICT gives forecasts where the regressors have values. APPLY repeats the previous AREG, or the model named in quotes (MOD_1, MOD_2, … in the order the session made them) with the subcommands given now replacing its own; INITIAL starts from its estimates, FIT uses them as they are.

Example

AREG heating_cost WITH degree_days /METHOD=CO /RHO=0.3.

statscraft help AREG prints the same text in the terminal. All commands

Statscraft 0.61.0, release v0.61.0

SPECTRA

Periodogram, smoothed spectral density and cross-spectra of series.

Syntax

SPECTRA VARIABLES= series [/CENTER [NO]] [/CROSS [NO]]
        [/WINDOW=HAMMING | TUKEY | PARZEN | BARTLETT | UNIT | DANIELL [(span)] | NONE | weights]
        [/PLOT=P S CS QS PH A G K ALL NONE [BY FREQ | BY PERIOD]]
        [/SAVE=FREQ(root) PER(root) SIN(root) COS(root) P(root) S(root) RC(root) IC(root)
               CS(root) QS(root) PH(root) A(root) G(root) K(root)] [/APPLY].

The terms are listed for the frequencies K/n, K = 0 to n/2: the sine and cosine coefficients and the periodogram (a^2 + b^2) n/2. A series needs six cases and no missing values (use USE or RMV); of an odd count the first case is dropped. CENTER subtracts the mean, else the periodogram at frequency 0 is 2n times its square. The density is a moving average of the periodogram whose weights come from the window’s kernel at the span’s own frequencies, scaled to sum to 1; the default is HAMMING(5), an even span loses one, a span of 1 or NONE leaves the periodogram as it is, and a list of weights runs from the leftmost to the rightmost (an even list lacks the last one).

Values beyond the ends are mirrored. CROSS pairs the first series with each later one: real and imaginary cross-periodogram, cospectrum (CS), quadrature spectrum (QS), phase (PH, radians), cross amplitude (A), gain of the second series over the first (G) and squared coherency (K). Charts come as data, by frequency and by period unless BY picks one; P (the default) and S are drawn on natural logs. SAVE writes one variable per series (root_1, root_2 by their place on VARIABLES) or pair (root_1_2), FREQ and PER under the root itself, from the first case used; a name that exists is skipped. APPLY repeats the previous SPECTRA, or the model named in quotes (MOD_1, MOD_2, … in the order the session made them); SAVE is excepted.

Example

SPECTRA VARIABLES=river_flow rainfall /CENTER /CROSS /WINDOW=PARZEN(7) /PLOT=S K BY FREQ.

statscraft help SPECTRA prints the same text in the terminal. All commands

Statscraft 0.61.0, release v0.61.0

2SLS

Two-stage least squares for equations with endogenous predictors.

Syntax

2SLS [EQUATION=] dependent WITH predictors [/[EQUATION=] dependent WITH predictors]
     /INSTRUMENTS=variables [/ENDOGENOUS=variables] [/CONSTANT | /NOCONSTANT]
     [/PRINT=COV] [/SAVE=PRED RESID] [/APPLY].

The first stage regresses every predictor on the instruments (and the constant); the second regresses the dependent on those predicted values. A predictor that is also an instrument predicts itself, so naming every predictor as an instrument gives ordinary least squares. There must be at least as many instruments as predictors in the longest equation. Repeated INSTRUMENTS lists add up; ENDOGENOUS only documents the model. Case weights count, and a case missing on any variable of the command leaves every equation. Per equation: R, R square, the standard error and the mean of the residuals, an ANOVA table, the coefficients with standardized ones, t tests and tolerances, and the correlations of the estimates (PRINT=COV or TSET PRINT=DETAILED adds their covariances). Residuals use the observed predictors. TSET NEWVAR saves FIT_n and ERR_n per equation; SAVE picks them itself, always under free numbers. CONSTANT defaults to TSET. APPLY repeats the previous 2SLS, or the model named in quotes (MOD_1, MOD_2, … in the order the session made them), with the subcommands given now replacing its own.

Example

2SLS crop_yield WITH fertilizer_kg /INSTRUMENTS=subsidy_rate soil_ph /SAVE=RESID.

statscraft help 2SLS prints the same text in the terminal. All commands

Statscraft 0.61.0, release v0.61.0

TSMODEL

Exponential smoothing and ARIMA models of series, picked by hand or by the expert modeler, with forecasts.

Syntax

TSMODEL [/MODELSUMMARY [PRINT=[MODELFIT RESIDACF RESIDPACF | NONE]] [PLOT=[measures | RESIDACF | RESIDPACF]]]
        [/MODELSTATISTICS [DISPLAY=YES | NO] [MODELFIT=[SRSQUARE RSQUARE RMSE MAPE MAE MAXAPE MAXAE NORMBIC]]]
        [/MODELDETAILS [PRINT=[PARAMETERS RESIDACF RESIDPACF FORECASTS]] [PLOT=[RESIDACF RESIDPACF]]]
        [/SERIESPLOT OBSERVED FORECAST FIT FORECASTCI FITCI]
        [/OUTPUTFILTER [DISPLAY=ALLMODELS | [BESTFIT(N=n | PCT=p) WORSTFIT(N=n | PCT=p)]] [MODELFIT=measure]]
        [/SAVE PREDICTED[(root)] LCL[(root)] UCL[(root)] NRESIDUAL[(root)]]
        [/AUXILIARY [CILEVEL=95] [MAXACFLAGS=24] [SEASONLENGTH=n]] [/MISSING USERMISSING=EXCLUDE | INCLUDE]
        /MODEL DEPENDENT=series [INDEPENDENT=predictors] [OUTFILE=file] [PREFIX='Model']
        [/EXPERTMODELER [TYPE=[ARIMA EXSMOOTH]] [TRYSEASONAL=YES | NO]
         | /EXSMOOTH TYPE=SIMPLE | SIMPLESEASONAL | HOLT | BROWN | DAMPEDTREND | WINTERSADDITIVE
                     | WINTERSMULTIPLICATIVE [TRANSFORM=NONE | SQRT | LN]
         | /ARIMA AR=lags MA=lags [ARSEASONAL=lags] [MASEASONAL=lags] [DIFF=d] [DIFFSEASONAL=D]
                  [CONSTANT=YES | NO] [TRANSFORM=NONE | SQRT | LN]]
        [/TRANSFERFUNCTION [VARIABLES=ALL | predictors] [NUM=lags] [NUMSEASONAL=lags]
                           [DENOM=lags] [DENOMSEASONAL=lags] [DIFF=d] [DIFFSEASONAL=D]
                           [DELAY=b] [TRANSFORM=NONE | SQRT | LN]] ...
        [/AUTOOUTLIER DETECT=OFF | ON [TYPE=[ADDITIVE LEVELSHIFT INNOVATIONAL TRANSIENT
                     SEASONALADDITIVE LOCALTREND ADDITIVEPATCH]]]
        [/OUTLIER LOCATION=[case | date] TYPE=type] ... [/MODEL ...].

Every series of DEPENDENT gets its own model, named PREFIX_1, PREFIX_2 and so on. Global subcommands come first; words are written in full and a list goes in square brackets.

The season length is SEASONLENGTH, else the period of the DATE variables. The model is estimated over the USE range less missing values at its ends; forecasts run from the case after it to the end of PREDICT. Smoothing weights minimize the sum of squared one-step errors, from start values found by smoothing backwards. ARIMA models are fitted by exact maximum likelihood; a single lag value is an order (AR=2: lags 1 and 2), a list of two or more names the lags. In a custom ARIMA model each predictor passes through a ratio of lag polynomials: TRANSFERFUNCTION sets the numerator lags (lag 0 is always in) and denominator lags, plain and seasonal, and how the predictor is transformed, differenced and shifted by DELAY first; the last one naming a predictor counts. Without it a predictor enters at lag 0, and the expert modeler enters every predictor so ([E] after a name is accepted). OUTLIER puts an outlier of the type given at a case number or a DATE point; AUTOOUTLIER DETECT=ON searches the ARIMA model (custom or expert) for outliers of the types listed (additive and level shift by default), keeping those that stay significant when estimated with the model. The expert modeler fits every fitting smoothing method and a search of ARIMA orders and keeps the model with the smallest normalized BIC. Output: the model description, a summary of the fit measures across models, a table of the fit measures, the Ljung-Box Q(18) and the number of outliers by model, and on request parameters (with an Outliers table), residual autocorrelations, forecasts and charts. MODELSUMMARY PLOT draws a histogram of each fit measure named (the names of MODELFIT), one value per model, and for RESIDACF and RESIDPACF a boxplot per lag of the models’ residual autocorrelations (they need reestimation). OUTFILE writes the models to a JSON file for TSAPPLY. SAVE adds root_series_model variables (Predicted, LCL, UCL, NResidual).

Example

TSMODEL /MODELDETAILS PRINT=[PARAMETERS FORECASTS] /MODEL DEPENDENT=bookings /EXSMOOTH TYPE=HOLT.

statscraft help TSMODEL prints the same text in the terminal. All commands

Statscraft 0.61.0, release v0.61.0

TSAPPLY

Forecasts from time series models that TSMODEL saved, as they are or estimated again.

Syntax

TSAPPLY [global subcommands of TSMODEL] [/AUXILIARY [REESTIMATE=NO | YES] ...]
        /MODEL FILE=file [DROP=['id' ...] | KEEP=['id' ...]] [OUTFILE=file] [/MODEL ...].

Reads the JSON model files TSMODEL writes and applies each model to the series of the same name. With REESTIMATE=NO (the default) the saved estimates and the saved series make the forecasts, which start after the case the model was estimated to, counted from the first case of the file; the fit measures are the saved ones. REESTIMATE=YES keeps the form of each model and estimates it again over the USE range of the active dataset.

KEEP and DROP pick models by identifier; OUTFILE writes the models applied. Output and SAVE are as in TSMODEL; residual autocorrelations, fitted values and residuals need REESTIMATE=YES. It does not run under SPLIT FILE.

Example

TSAPPLY /MODELDETAILS PRINT=FORECASTS /MODEL FILE='bookings_models.json'.

statscraft help TSAPPLY prints the same text in the terminal. All commands

Statscraft 0.61.0, release v0.61.0

TSPLOT

Chart of time series over the cases, as chart data.

Syntax

TSPLOT [VARIABLES=] series [/DIFF[=n]] [/SDIFF[=n]] [/PERIOD=n] [/LN | /NOLOG]
       [/ID=variable] [/MARK=variable | date] [/SPLIT=UNIFORM | SCALE]
       [/FORMAT=[NOFILL | BOTTOM] [NOREFERENCE | REFERENCE[(value)]] | NOJOIN | JOIN | HILO]
       [/APPLY].

The cases run along the horizontal axis, labeled by ID (else TSET ID, else DATE_, else the case number). Each series may be logged first (LN; values not above 0 become missing), then differenced DIFF times and over the period SDIFF times (DIFF or SDIFF alone: once); the period is PERIOD, TSET PERIOD or that of the DATE variables, and without one SDIFF is skipped with a warning. With one series, BOTTOM fills the area under the line (only when no value is missing or negative) and REFERENCE adds a flat line at the value or at the series mean. With several, JOIN links the values of each case and HILO shows only the highest and lowest of each case (up to three series). MARK names the cases where a variable changes, or a date given with DATE keywords, in the footnote, which also lists the transformations. Under SPLIT FILE each group gets a chart; the reference mean is the group’s. USE limits the cases. APPLY repeats the previous TSPLOT, or the model named in quotes (MOD_1, MOD_2, … in the order the session made them), with the subcommands given now replacing its own.

Example

TSPLOT VARIABLES=river_level rainfall /FORMAT=JOIN /MARK=dam_open.

statscraft help TSPLOT prints the same text in the terminal. All commands

Statscraft 0.61.0, release v0.61.0

CASEPLOT

Chart of time series with the cases down the vertical axis, as chart data.

Syntax

CASEPLOT [VARIABLES=] series [/DIFF[=n]] [/SDIFF[=n]] [/PERIOD=n] [/LN | /NOLOG]
         [/ID=variable] [/MARK=variable | date] [/SPLIT=UNIFORM | SCALE]
         [/FORMAT=[NOFILL | LEFT] [NOREFERENCE | REFERENCE[(value)]] | NOJOIN | JOIN | HILO]
         [/APPLY].

TSPLOT turned on its side: the cases run down the vertical axis and the values across.

LEFT fills the area between the axis and the line of a single series. Everything else is as for TSPLOT.

Example

CASEPLOT VARIABLES=hourly_load /ID=shift /FORMAT=LEFT.

statscraft help CASEPLOT prints the same text in the terminal. All commands

Statscraft 0.61.0, release v0.61.0

FIT

Goodness-of-fit statistics of residual series from time series models.

Syntax

FIT [[ERRORS=] residual series] [/OBS=observed series] [/DFE=n ... | /DFH=n ...].

For each residual series e over n cases: the mean error, the mean absolute error, the sum of squared errors, the mean square error (the sum over the error degrees of freedom), its square root and the Durbin-Watson statistic. With OBS (one observed series per residual series, in order, repeated where several residual series come from one) also the mean percent error and the mean absolute percent error, 100 times the mean of e/x. Without any names it takes the last ERR_n series a procedure saved, with the series it was made from. DFE gives the error degrees of freedom of each residual series and DFH the model’s parameters, which are taken from the cases; with neither the cases count. A PREDICT period that starts inside the series gets its own columns next to the USE period’s. A case with a missing residual is left out; the percent statistics also leave out a case whose observed value is missing or 0. With SPLIT FILE each group is a block of rows in the one table.

Example

FIT ERRORS=ERR_1 ERR_2 /OBS=sales sales /DFH=2 3.

statscraft help FIT prints the same text in the terminal. All commands

Statscraft 0.61.0, release v0.61.0

自定义表格

命令功能 {#what-it-does}
CTABLESCustom tables: counts, percentages and statistics by categories.
DMTABLESAnother name for CTABLES.
MRSETSDefine, delete and list multiple response sets.

All commands

Statscraft 0.61.0, release v0.61.0

CTABLES

Custom tables: counts, percentages and statistics by categories.

Syntax

CTABLES [/FORMAT EMPTY=ZERO|BLANK|'text' MISSING='text']
        [/VLABELS VARIABLES=varlist DISPLAY=DEFAULT|NAME|LABEL|BOTH|NONE]
        [/MRSETS COUNTDUPLICATES=NO|YES]
        [/HIDESMALLCOUNTS [COUNT=5]] [/WEIGHT VARIABLE=varname] [/SMISSING VARIABLE|LISTWISE]
        [/PCOMPUTE &name=EXPR(expression)]
        [/PPROPERTIES &name ... [LABEL='text'] [FORMAT=function format ...] [HIDESOURCECATS=NO|YES]]
        /TABLE [rows] [BY [columns] [BY layers]]
        [/SLABELS POSITION=COLUMN|ROW|LAYER VISIBLE=YES|NO]
        [/CLABELS AUTO|ROWLABELS=OPPOSITE|LAYER|COLLABELS=OPPOSITE|LAYER] [/CRITERIA CILEVEL=95]
        [/CATEGORIES VARIABLES=varlist [ORDER=A|D] [KEY=VALUE|LABEL|function[(var[, n])]]
                     [MISSING=EXCLUDE|INCLUDE]
                     [TOTAL=NO|YES] [LABEL='text'] [POSITION=AFTER|BEFORE] [EMPTY=INCLUDE|EXCLUDE]]
        [/CATEGORIES VARIABLES=varlist [value, low THRU high, OTHERNM, MISSING, &name,
                     SUBTOTAL='label', HSUBTOTAL='label', ...] [TOTAL=YES ...]]
        [/TITLES TITLE='text' ['text' ...] CAPTION='text' ... CORNER='text' ...]
        [/SIGTEST TYPE=CHISQUARE [ALPHA=0.05] [INCLUDEMRSETS=YES|NO] [CATEGORIES=ALLVISIBLE|SUBTOTALS]]
        [/COMPARETEST TYPE=PROP|MEAN [ALPHA=0.05 [0.01]] [ADJUST=BONFERRONI|BH|NONE]
                      [MEANSVARIANCE=ALLCATS|TESTEDCATS] [SHOWSIG=NO|YES] [INCLUDEMRSETS=YES|NO]
                      [CATEGORIES=ALLVISIBLE|SUBTOTALS] [MERGE=NO|YES [STYLE=APA|SIMPLE]]
                      [ORIGIN=COLUMN]]
        [/TABLE ... another table with its own SLABELS, CATEGORIES, TITLES and tests].

The command builds tables of counts, percentages and statistics. Each /TABLE is rows BY columns BY layers. On an axis, + stacks variables, > nests them (a > b: b within each category of a), and parentheses group. A [C] or [S] after a variable makes it categorical or scale. Otherwise level SCALE is scale and other levels categorical; a numeric variable of unknown level is scale with a currency, date or time format, a fraction, a negative value, 24 or more distinct values, or no value below 10. /TABLE BY columns gives one unlabeled row. SLABELS, CLABELS, CATEGORIES, TITLES, CRITERIA and the tests belong to the /TABLE before them.

The default summary is COUNT, or MEAN for a scale variable. A summary list follows a scale variable or the innermost categorical variable of an axis: var [function [‘label’] [format], …]; a function given twice is two columns. In (a + b > c) [COUNT] the summaries go to a and c, before their own. Categorical functions: COUNT, ROWPCT, COLPCT, TABLEPCT, SUBTABLEPCT, LAYERPCT, LAYERROWPCT, LAYERCOLPCT; a percentage takes the base .COUNT (default), .VALIDN or .TOTALN. Scale variables add MEAN MEDIAN MODE MINIMUM MAXIMUM RANGE SUM STDDEV VARIANCE SEMEAN PTILE n VALIDN TOTALN MISSING and the percentages with .SUM. A U prefix (UCOUNT) ignores the weight. TOTALS [function …] in a categorical variable’s list gives its totals and subtotals their own summaries (the columns hold both lists); a scale function there summarizes the variable’s own values: var [COUNT TOTALS [MEAN]].

Formats: F, PCT, COMMA, DOT (period and comma swapped), DOLLAR, N (leading zeros), E, CCA to CCE, date and time formats, and NEGPAREN (negatives in parentheses), NEQUAL (N= before), PAREN and PCTPAREN, which show F in the width with their marks outside it. A scale summary has the variable’s format, but for dates STDDEV, SEMEAN and RANGE show DTIME, and SUM and VARIANCE (also of times) plain numbers.

CATEGORIES VARIABLES=varlist sorts by ORDER=A (default) or D and KEY=VALUE (default), LABEL or a summary of each category over all its cases (COUNT, MEAN(age), PTILE(age, 75)); ties keep value order. TOTAL=YES adds a total named by LABEL, placed by POSITION=AFTER (default) or BEFORE; its percentage base takes in every category totaled. EMPTY=EXCLUDE hides categories without cases. User-missing categories show only with MISSING=INCLUDE, system-missing ones never. An empty count shows 0, or blank or text with FORMAT EMPTY; FORMAT MISSING=‘text’ fills cells that cannot be computed (else blank).

An explicit list fixes the categories and their order: VARIABLES=q1 [3, 1, 4 THRU 6, OTHERNM, MISSING]. OTHERNM is every valid value not named, ascending; MISSING every user-missing value; a value named twice takes its last place; KEY does not apply. A case whose valid value is not listed is not in the table. SUBTOTAL=‘label’ sums the categories before it back to the previous subtotal (with POSITION=BEFORE, those after it up to the next); HSUBTOTAL also hides them. A subtotal counts a case once and has every summary a total has.

Layers (rows BY columns BY layers, or rows BY BY layers) give a table per layer category, titled by it: every combination of nested layer variables and every category of stacked ones. Percentages stay within the layer (LAYERPCT: all its cells; LAYERROWPCT, LAYERCOLPCT: across its subtables), except TABLEPCT, which spans all layers. Tests run in every layer.

SLABELS POSITION puts summary labels in the columns (default), rows or layers (each summary a layer); VISIBLE=NO hides them. CLABELS ROWLABELS=OPPOSITE moves the innermost row categories to the columns, inside the column categories and outside the summary labels; COLLABELS=OPPOSITE does the reverse. The moved variable is then the innermost of its new axis, also for percentages. ROWLABELS=LAYER or COLLABELS=LAYER makes each category a layer and the variable a layer variable. Moved stacked variables need the same categories and labels, and tests are then unavailable. AUTO (default) moves nothing.

TITLES takes TITLE, CAPTION and CORNER; several quoted texts are several lines. )DATE is today’s date (YYYY-MM-DD), )TIME the time (HH:MM:SS), both local, and )TABLE the table expression with labels, without levels and summaries: Gender > Age BY Region. VLABELS sets the headings of the named variables: DEFAULT, NAME, LABEL, BOTH or NONE.

A case whose missing value is left out still counts in TOTALN and the .TOTALN percentages. SMISSING LISTWISE (default VARIABLE) makes a case missing on one scale variable missing on all scale variables of the table (the sections with the same categorical variables); it still counts in COUNT and TOTALN. The weight variable applies unrounded; a case with zero, negative or missing weight is left out, also from U functions. MEDIAN and PTILE use the averaged empirical distribution. HIDESMALLCOUNTS COUNT=n (whole, from 2, default 5) shows every COUNT, VALIDN, TOTALN or RESPONSES below n, weighted or with U, as <n in all tables.

Tests run in every innermost subtable (innermost row by innermost column variable, per category of the outer ones), each in a table after the main one. They compare the shown categories, an HSUBTOTAL standing for those it hides; CATEGORIES=SUBTOTALS puts every subtotal in place of its categories. With a weight variable they round the weighted cell counts, column totals or category weights. SIGTEST TYPE=CHISQUARE (required) gives the Pearson chi-square, without empty rows and columns. The chi-square test and COMPARETEST TYPE=PROP need two different variables on the rows and the columns, and cell counts or row or column percentages of the counts in the table (weighted ones when the cases are weighted); a table that lacks them is left out, with a reason in the note.

COMPARETEST TYPE=PROP gives two-sided pairwise z-tests of column proportions, TYPE=MEAN t-tests of column means (a scale variable with MEAN in the rows), in every row of a subtable; a table may have one of each. The letter of the smaller column appears in the larger one: uppercase below the smaller ALPHA, lowercase below the larger (one or two levels, default 0.05). A period marks a column left out (a proportion of 0 or 1, or under 2 cases). ADJUST is BONFERRONI (default), BH or NONE; MEANSVARIANCE ALLCATS (default) or TESTEDCATS. ORIGIN=COLUMN changes nothing. MERGE=YES puts the letters in the main table, in a column after each compared category (in the row of MEAN, COLPCT or COUNT when summaries are in rows). STYLE=APA (default) gives two columns a shared letter unless they differ at the smaller ALPHA; SIMPLE gives the separate table’s keys. SHOWSIG=YES keeps the separate table.

A multiple response set ($name, see MRSETS) stands where a categorical variable may. A case counts once in each category it responds in; the set’s total counts cases with any response; a case with none counts only in TOTALN and the .TOTALN percentages. A dichotomy set lists its variables in set order, also by name in CATEGORIES: [q5_3, q5_1]. A set may carry the summaries with categorical variables nested in it; of two nested sets only the inner one may. Sets add RESPONSES and, for every percentage base, base.RESPONSES (responses over the area’s responses), base.RESPONSES.COUNT (responses over its count) and base.COUNT.RESPONSES (count over its responses). MRSETS COUNTDUPLICATES=YES counts a value given in two variables of a category set twice in the responses, never in counts.

Tests include sets (INCLUDEMRSETS=YES, default), counting each case once in the margins and allowing for cases two categories share; the means test then pools the variance of the two categories compared. INCLUDEMRSETS=NO, or COUNTDUPLICATES=YES for a category set, leaves sets out.

PCOMPUTE &name=EXPR(expression) defines a computed category for an explicit category list. For every summary it combines the same summary of [value], [low THRU high] (the sum of the listed categories in range), TOTAL (needs TOTAL=YES), SUBTOTAL (the only one) or SUBTOTAL[n], [OTHERNM] and [MISSING], with numbers, + - * / ** and parentheses. Every category it names must be listed. PPROPERTIES sets its LABEL (default the expression; )LABEL[n] is the label of the nth list item as written, a range as ‘low THRU high’), a FORMAT per summary, and HIDESOURCECATS=YES to hide its source categories (not with tests). Totals and tests leave computed categories out.

A .LCL, .UCL or .SE suffix gives confidence limits or a standard error (COUNT.LCL, COLPCT.COUNT.UCL, MEAN.SE): limits for COUNT, the percentages of COUNT, VALIDN or TOTALN, MEAN, MEDIAN, PTILE and SUM; .SE for COUNT, those percentages, MEAN and SUM; neither for sets or U functions. CRITERIA CILEVEL (default 95) sets the level of its table. Proportions and counts use the Jeffreys interval (weights rounded), means and sums the t interval.

/WEIGHT VARIABLE=var (before the first /TABLE) weights all tables by an effective base weight instead of the WEIGHT command’s variable. ECOUNT (also for categorical variables and sets), EVALIDN and ETOTALN then give the effective bases, (sum of weights)^2 / (sum of squared weights), of COUNT, VALIDN and TOTALN, which they equal without /WEIGHT. SEMEAN uses the variance adjusted to the effective base. The tests use the effective bases and round nothing; the column t-tests compare two categories when both have a case and one has two.

DMTABLES is another name for the command.

Example

GET FILE='survey.sav'.
CTABLES /TABLE satisfaction [COUNT, COLPCT.COUNT PCT5.1] BY region
  /CATEGORIES VARIABLES=satisfaction TOTAL=YES.
CTABLES /TABLE region > gender BY spend [MEAN F5.1, MEDIAN F5.1, COUNT].
CTABLES /TABLE $channels [COLPCT.RESPONSES.COUNT PCT5.1] BY age_group
  /SIGTEST TYPE=CHISQUARE /COMPARETEST TYPE=PROP ALPHA=0.05.

The example reads the sample data file survey.sav, an invented customer survey; save it in the folder you run the syntax from.

Example output

Custom Tables

Region / North / CountRegion / North / Column %Region / South / CountRegion / South / Column %Region / East / CountRegion / East / Column %Region / West / CountRegion / West / Column %
Overall satisfaction with the serviceVery dissatisfied34.3%46.9%1115.1%22.6%
Overall satisfaction with the serviceDissatisfied1420.0%58.6%2534.2%2228.9%
Overall satisfaction with the serviceNeutral1115.7%1932.8%2635.6%2938.2%
Overall satisfaction with the serviceSatisfied2637.1%1627.6%912.3%1215.8%
Overall satisfaction with the serviceVery satisfied1622.9%1424.1%22.7%1114.5%
Overall satisfaction with the serviceTotal70100.0%58100.0%73100.0%76100.0%

statscraft help CTABLES prints the same text in the terminal. All commands

Statscraft 0.61.0, release v0.61.0

DMTABLES

Another name for CTABLES.

Syntax

DMTABLES [/subcommands of CTABLES].

The same command as CTABLES, with the same subcommands and defaults.

Example

DMTABLES /TABLE region BY bought [COUNT, ROWPCT.COUNT].

statscraft help DMTABLES prints the same text in the terminal. All commands

Statscraft 0.61.0, release v0.61.0

MRSETS

Define, delete and list multiple response sets.

Syntax

MRSETS [/]MDGROUP NAME=$name [LABEL='text' | LABELSOURCE=VARLABEL] [CATEGORYLABELS=VARLABELS | COUNTEDVALUES]
       VARIABLES=varlist VALUE=value
       /MCGROUP NAME=$name [LABEL='text'] VARIABLES=varlist
       /DELETE NAME=[$name ...] | ALL
       /DISPLAY NAME=[$name ...] | ALL.

Subcommands run in the order written and may repeat. A set name starts with $; defining an existing name replaces that set. A set has at least two variables, all numeric or all strings.

MDGROUP (dichotomies): every variable is one category, labeled with its variable label or name; a case has a response in it when the variable holds VALUE, a whole number or, for strings, a quoted text no wider than the narrowest variable. CATEGORYLABELS=COUNTEDVALUES labels each category with the value label of VALUE in its variable instead; every variable needs one and they must differ.

LABELSOURCE=VARLABEL (only with COUNTEDVALUES, instead of LABEL) takes the set label from the first variable of the set that has a variable label, else the name of the first variable.

MCGROUP (categories): the values of the variables are the categories, labeled with the value labels of the first variable that has one.

DISPLAY lists the sets in a table. Sets are saved with the data file and used by CTABLES.

Example

GET FILE='survey.sav'.
MRSETS /DISPLAY NAME=ALL.
MRSETS /MDGROUP NAME=$digital LABEL='Digital channels'
  VARIABLES=ch_web ch_app ch_email VALUE=1
  /DISPLAY NAME=[$digital].
CTABLES /TABLE $digital [COUNT, COLPCT.COUNT PCT5.1] BY region.

The example reads the sample data file survey.sav, an invented customer survey; save it in the folder you run the syntax from.

Example output

Multiple Response Sets

NameLabelTypeCounted valueVariables
$channelsChannels usedMultiple dichotomy1ch_web ch_app ch_phone ch_store ch_email

statscraft help MRSETS prints the same text in the terminal. All commands

Statscraft 0.61.0, release v0.61.0

Complex samples

命令功能 {#what-it-does}
CSPLANWrite or show the plan of a complex sample: how to draw it, or how to analyze it.
CSSELECTDraw a complex sample from the active dataset by a plan written by CSPLAN SAMPLE.
CSDESCRIPTIVESMeans, sums and ratios of a complex sample with design-based standard errors and design effects.
CSTABULATEOne-way and two-way tables of a complex sample with design-based errors and adjusted tests.
CSGLMLinear regression, ANOVA and ANCOVA on a complex sample, with design-based standard errors and tests.
CSLOGISTICBinary and multinomial logistic regression on a complex sample, with design-based standard errors and tests.
CSORDINALOrdinal regression (cumulative link model) on a complex sample, with design-based standard errors and tests.
CSCOXREGCox proportional hazards regression on a complex sample, with design-based standard errors and tests.

All commands

Statscraft 0.61.0, release v0.61.0

CSPLAN

Write or show the plan of a complex sample: how to draw it, or how to analyze it.

Syntax

CSPLAN SAMPLE /PLAN FILE='file' [/PLANVARS [SAMPLEWEIGHT=var] [PREVIOUSWEIGHT=var]]
   [/PRINT [PLAN] [MATRIX]]
   /DESIGN [STAGELABEL='label'] [STRATA=vars] [CLUSTER=vars]
   /METHOD TYPE=SIMPLE_WOR | SIMPLE_WR | SIMPLE_SYSTEMATIC | SIMPLE_CHROMY | PPS_WOR | PPS_WR
               | PPS_SYSTEMATIC | PPS_BREWER | PPS_MURTHY | PPS_SAMPFORD | PPS_CHROMY
               [ESTIMATION=DEFAULT | WR]
   /SIZE VALUE=n | VARIABLE=var | MATRIX=vars; categories n; ...
   | /RATE VALUE=f | VARIABLE=var | MATRIX=vars; categories f; ... [MINSIZE=n] [MAXSIZE=n]
   [/MOS VARIABLE=var | SOURCE=FROMDATA [MIN=m] [MAX=m]]
   [/STAGEVARS [INCLPROB[(var)]] [CUMWEIGHT[(var)]] [INDEX[(var)]] [POPSIZE[(var)]]
              [SAMPSIZE[(var)]] [RATE[(var)]] [WEIGHT[(var)]]]
   [/DESIGN ... /METHOD ... (a second and a third stage)].
CSPLAN ANALYSIS /PLAN FILE='file' /PLANVARS ANALYSISWEIGHT=var [/SRSESTIMATOR TYPE=WOR | WR]
   [/PRINT [PLAN] [MATRIX]]
   /DESIGN [STAGELABEL='label'] [STRATA=vars] [CLUSTER=vars]
   /ESTIMATOR TYPE=EQUAL_WOR | UNEQUAL_WOR | WR
   [/POPSIZE VALUE=n | VARIABLE=var | MATRIX=vars; categories n; ...]
   [/INCLPROB VALUE=p | VARIABLE=var | MATRIX=vars; categories p; ...]
   [/DESIGN ... /ESTIMATOR ... (a second and a third stage)].
CSPLAN VIEW /PLAN FILE='file' [/PRINT [PLAN] [MATRIX]].

The plan is a small JSON file that the other CS commands read; CSPLAN does not read the data. Each DESIGN starts a stage, and the subcommands after it belong to that stage.

A stage followed by another needs CLUSTER.

SAMPLE plans are carried out by CSSELECT. Per stage, METHOD says how units are drawn inside each stratum: SIMPLE_WOR at random without replacement, SIMPLE_WR with replacement (last stage only), SIMPLE_SYSTEMATIC every N/n-th unit from a random start, SIMPLE_CHROMY sequentially with Chromy’s method. The PPS methods (first stage only) give each unit a chance in proportion to its measure of size, MOS: a variable, or with SOURCE=FROMDATA the number of cases in the cluster, held between MIN and MAX. PPS_WOR (Hanurav and Vijayan), PPS_SAMPFORD, PPS_BREWER and PPS_MURTHY (these two draw two units) draw without replacement, need CLUSTER and are analyzed as UNEQUAL_WOR; PPS_WR, PPS_SYSTEMATIC and PPS_CHROMY are analyzed as WR. A unit too large for its share of the sample is taken for sure. SIZE gives the number of units per stratum, RATE the share (n is the share times the population rounded, then raised to MINSIZE or lowered to MAXSIZE); either one as a value, a variable that holds it, or a matrix with a row per stratum. STAGEVARS renames the variables CSSELECT writes and asks for more: the inclusion probability and the cumulative weight are always written (InclusionProbability_1_ and SampleWeightCumulative_1_ for stage 1), the duplicate index for a stage drawn with replacement, and on request the population size, sample size, rate and weight of the stage.

The final weight (SAMPLEWEIGHT, default SampleWeight_Final_) multiplies the stage weights and PREVIOUSWEIGHT. A sample plan is an analysis plan too: SIMPLE_WOR stages are analyzed as EQUAL_WOR with the inclusion probability variable, the PPS methods as said above, the others as WR (and every stage as WR with ESTIMATION=WR, first stage only), so CSDESCRIPTIVES can read the plan of a drawn sample.

ANALYSIS plans describe a sample drawn elsewhere. WR treats the units of the stage as drawn with replacement and ends the design: later stages add nothing to the variance. EQUAL_WOR treats them as drawn without replacement with equal chances and needs either the population size of each stratum (POPSIZE, whole numbers) or the share of units drawn (INCLPROB, above 0 and at most 1); it brings the finite population correction. UNEQUAL_WOR (first stage, with CLUSTER) treats the units as drawn without replacement with unequal chances: the analysis reads their inclusion and joint inclusion probabilities from the file CSSELECT writes (see JOINTPROB of CSDESCRIPTIVES). SRSESTIMATOR picks the simple random sampling variance that design effects compare with: WOR (the default) includes the finite population correction, WR does not.

PRINT PLAN (the default) shows the plan, MATRIX the matrix rows.

Example

CSPLAN SAMPLE /PLAN FILE='orchards_draw.json' /DESIGN STRATA=valley CLUSTER=orchard /METHOD TYPE=SIMPLE_WOR /SIZE VALUE=3 /DESIGN /METHOD TYPE=SIMPLE_SYSTEMATIC /RATE VALUE=0.25 MINSIZE=2.

statscraft help CSPLAN prints the same text in the terminal. All commands

Statscraft 0.61.0, release v0.61.0

CSSELECT

Draw a complex sample from the active dataset by a plan written by CSPLAN SAMPLE.

Syntax

CSSELECT /PLAN FILE='file' [/CRITERIA [STAGES=n [n [n]]] [SEED=RANDOM | n]]
   [/CLASSMISSING EXCLUDE | INCLUDE] [/DATA [RENAMEVARS] [PRESORTED]]
   [/SAMPLEFILE OUTFILE='file' | dataset [KEEP=vars] [DROP=vars]]
   [/JOINTPROB OUTFILE='file'] [/SELECTRULE OUTFILE='file'] [/PRINT [SELECTION] [CPS]].

The active dataset is the frame. Stage by stage, the units (cases, or the combinations of the CLUSTER values) are drawn inside each stratum; a later stage draws only inside the units the earlier one selected. STAGES runs part of the plan: a later stage then needs the cumulative weight variable of the stage before it in the data. A case with a missing stratum or cluster (user-missing ones count under CLASSMISSING=INCLUDE), or a missing size, rate or previous weight, is not part of the frame. FILTER and USE limit the frame; WEIGHT and SPLIT FILE are ignored with a warning.

SEED=n makes the draw repeatable and leaves the session’s generator alone. Without it the seed comes from the session’s generator when SET SEED was given in the session, so the same syntax draws the same sample again; otherwise from the clock.

Without SAMPLEFILE the new variables join the active dataset, which keeps every case: a case outside the sample has missing weights. SAMPLEFILE writes the selected cases only, with the variables KEEP and DROP leave (applied in their order) and the new ones; a unit drawn several times with replacement appears once per draw, numbered by the index variable. A plan that draws with replacement needs SAMPLEFILE. A new variable whose name already exists is an error; with RENAMEVARS the existing variable is renamed to the first free name of the form name_1, name_2, … with a warning.

Stage inclusion probabilities are n/N (with replacement 1 - (1 - 1/N)^n) and stage weights N/n per draw; with a PPS method n times the unit’s share of the total size (PPS_WR: 1 - (1 - share)^n, weight one over n times the share; PPS_MURTHY its own formula), and a measure of size must be the same in all cases of a unit. PRINT SELECTION (the default) shows per stage and stratum the population size, the sample size and the rate; CPS counts the cases. A first stage drawn by PPS_WOR, PPS_BREWER, PPS_MURTHY or PPS_SAMPFORD also writes the joint inclusion probabilities of the selected units to a data file: JOINTPROB OUTFILE, or else the plan’s name with the extension .joint.sav. It holds the first-stage strata and clusters, Unit_No_ (the unit’s number in its stratum) and Joint_Prob_k_ for k = 1, 2 and so on (the joint probability with unit k; the inclusion probability on the diagonal); with other plans JOINTPROB is ignored with a warning.

SELECTRULE OUTFILE writes a text file (replacing one of that name) with a condition that is true for the units drawn by the last stage run that has clusters, ready to turn into a SELECT IF or a database query for the next stage. Each unit is a line of comparisons (name EQ value) on the strata and clusters of its stage and of the stages above it, joined by AND; the lines are joined by OR; string values are quoted. When no stage run has clusters, the cases themselves are the units and nothing names them, so no file is written and a warning says so.

Example

CSSELECT /PLAN FILE='orchards_draw.json' /CRITERIA SEED=4711 /SAMPLEFILE OUTFILE='orchards_sample.sav' DROP=notes /PRINT SELECTION CPS.

statscraft help CSSELECT prints the same text in the terminal. All commands

Statscraft 0.61.0, release v0.61.0

CSDESCRIPTIVES

Means, sums and ratios of a complex sample with design-based standard errors and design effects.

Syntax

CSDESCRIPTIVES /PLAN FILE='file' [/SUMMARY VARIABLES=vars]
   [/MEAN [TTEST=value | values]] [/SUM [TTEST=value | values]]
   [/RATIO NUMERATOR=vars DENOMINATOR=vars [TTEST=value | values]] ...
   [/STATISTICS [COUNT] [POPSIZE] [SE] [CV] [DEFF] [DEFFSQRT] [CIN[(95)]]]
   [/SUBPOP TABLE=var [BY var ...] [DISPLAY=LAYERED | SEPARATE]]
   [/MISSING [SCOPE=ANALYSIS | LISTWISE] [CLASSMISSING=EXCLUDE | INCLUDE]]
   [/JOINTPROB FILE='file' | dataset].

The design comes from a plan written by CSPLAN; WEIGHT and SPLIT FILE do not apply. A case with a missing or non-positive weight, or a missing stratum, cluster, population size or inclusion probability, leaves the design. Totals are weighted sums; a mean is the total over the summed weights and a ratio is one total over another, and their variances come from Taylor linearization. The variance adds, stratum by stratum, the spread of the cluster totals, times the finite population correction under EQUAL_WOR, plus the variance of later stages. A stratum with one cluster adds nothing. Intervals and t tests use t with the number of first-stage clusters minus the number of first-stage strata as df. The design effect divides the variance by the one simple random sampling would give (see CSPLAN SRSESTIMATOR).

Each RATIO crosses its numerators with its denominators. Subpopulations are domains: their estimates use the whole design, with cases outside counting as zero; a Total row follows them. Under SCOPE=ANALYSIS each statistic uses the cases valid on its own variables, under LISTWISE those valid on all of them; the others count as outside, so the design stays whole.

Without STATISTICS: the estimate and its standard error. Under UNEQUAL_WOR a first-stage stratum adds, over each pair of its units, (pi_a pi_b / pi_ab - 1) times the squared difference of their totals (Yates and Grundy), with the inclusion and joint probabilities read from JOINTPROB FILE, or by default the file CSSELECT wrote next to the plan; a later stage counts times the unit’s inclusion probability. A negative variance is left empty.

Example

CSDESCRIPTIVES /PLAN FILE='farms_plan.json' /SUMMARY VARIABLES=yield acres /MEAN /RATIO NUMERATOR=yield DENOMINATOR=acres /STATISTICS SE CIN DEFF /SUBPOP TABLE=organic.

statscraft help CSDESCRIPTIVES prints the same text in the terminal. All commands

Statscraft 0.61.0, release v0.61.0

CSTABULATE

One-way and two-way tables of a complex sample with design-based errors and adjusted tests.

Syntax

CSTABULATE /PLAN FILE='file' /TABLES VARIABLES=vars [BY var]
   [/CELLS [POPSIZE] [ROWPCT] [COLPCT] [TABLEPCT]]
   [/STATISTICS [SE] [CV] [DEFF] [DEFFSQRT] [CIN[(95)]] [COUNT] [CUMULATIVE]
               [EXPECTED] [RESID] [ASRESID]]
   [/TEST [HOMOGENEITY] [INDEPENDENCE] [ODDSRATIO] [RELRISK] [RISKDIFF]]
   [/SUBPOP TABLE=var [BY var ...] [DISPLAY=LAYERED | SEPARATE]]
   [/MISSING [SCOPE=TABLE | LISTWISE] [CLASSMISSING=EXCLUDE | INCLUDE]]
   [/JOINTPROB FILE='file' | dataset].

Each variable gets a one-way table, or with BY a two-way table against the BY variable, with estimated population sizes and percents for every cell and margin. The design comes from a CSPLAN plan, as in CSDESCRIPTIVES, and so do the standard errors, df and design effects.

Percents are ratios of population sizes; their intervals are found on the logit scale.

CUMULATIVE (one-way) adds running sums. EXPECTED, RESID and ASRESID (two-way, with TABLEPCT) show the table percent expected under independence, the difference from it and that difference over its design-based standard error. HOMOGENEITY tests equal shares of a one-way table, INDEPENDENCE the rows against the columns: the Pearson and likelihood ratio chi-squares are divided by the sum of the generalized design effects and referred to F with d and d times the design df, d being the squared sum over the sum of squares of those effects (a second-order adjustment). ODDSRATIO, RELRISK and RISKDIFF give the 2 x 2 measures with intervals (log scale for the first two). Tests are for the whole population, and also for each subpopulation when SUBPOP names only first-stage strata. Without CELLS: population sizes; without STATISTICS: standard errors. JOINTPROB works as in CSDESCRIPTIVES.

Example

CSTABULATE /PLAN FILE='farms_plan.json' /TABLES VARIABLES=irrigated BY organic /CELLS POPSIZE ROWPCT /STATISTICS SE CIN DEFF /TEST INDEPENDENCE ODDSRATIO.

statscraft help CSTABULATE prints the same text in the terminal. All commands

Statscraft 0.61.0, release v0.61.0

CSGLM

Linear regression, ANOVA and ANCOVA on a complex sample, with design-based standard errors and tests.

Syntax

CSGLM dependent [BY factors] [WITH covariates] /PLAN FILE='file'
   [/MODEL effects] [/INTERCEPT [INCLUDE=YES | NO | ONLY] [SHOW=YES | NO]]
   [/CUSTOM [LABEL='text'] [LMATRIX=[c] effect values ... | ALL values; ...] [KMATRIX=k; ...]] ...
   [/EMMEANS [TABLES=factor[*factor ...]] [OTHER=[covariate(value | MEAN) ...]]
            [COMPARE=factor] [CONTRAST=SIMPLE[(value)] | DEVIATION[(value)] | DIFFERENCE |
                                    HELMERT | REPEATED | POLYNOMIAL[(metric)]]] ...
   [/CRITERIA [CILEVEL=95] [DF=n] [SINGULAR=1E-12]]
   [/STATISTICS [PARAMETER] [SE] [TTEST] [CINTERVAL] [DEFF] [DEFFSQRT]]
   [/TEST [TYPE=F | ADJF | CHISQUARE | ADJCHISQUARE]
          [PADJUST=LSD | BONFERRONI | SEQBONFERRONI | SIDAK | SEQSIDAK]]
   [/DOMAIN VARIABLE=var(value)] [/MISSING CLASSMISSING=EXCLUDE | INCLUDE]
   [/PRINT [SAMPLEINFO] [VARIABLEINFO] [SUMMARY] [GEF] [LMATRIX] [COVB] [CORB] [NONE]]
   [/SAVE [PRED[(name)]] [RESID[(name)]]]
   [/OUTFILE [COVB='file' | CORB='file'] [MODEL='file' | PARAMETER='file']].

The plan written by CSPLAN gives the weight and the design; WEIGHT and SPLIT FILE do not apply. The coefficients solve the weighted normal equations, with one parameter per level of each factor effect; a parameter that depends on earlier ones is redundant and set to 0. The covariance of the coefficients is a sandwich: the inverse of X’WX on both sides of the design covariance of the total of x times the residual, found as in CSDESCRIPTIVES. Every df is the number of first-stage clusters minus the number of first-stage strata, unless CRITERIA DF sets it. Without MODEL the model has the intercept, the factors and the covariates. Tests of Model Effects use Type III hypotheses: TYPE=F gives the Wald F, (df - r + 1) / (r df) times the Wald chi-square, on r and df - r + 1 df; ADJF divides the chi-square of the simple random sampling covariance by the sum of the generalized design effects, on d and d times df (d as in CSTABULATE); CHISQUARE and ADJCHISQUARE give the two chi-squares. CUSTOM tests L b = K row by row and as a whole; EMMEANS gives the means of the factor cells averaged with equal weights, covariates at their weighted means unless OTHER sets them, and COMPARE tests the contrasts of one factor. PADJUST adjusts the p values of the single rows. DOMAIN analyzes the cases with the value, keeping the whole design; cases with a missing value on a model variable count as outside it. R Square compares the weighted residual sum of squares with the weighted total sum of squares. Without STATISTICS the estimates come with SE, interval and t test. OUTFILE COVB writes, to a data file or a dataset made by DATASET DECLARE, the variables RowType_ and VarName_ and P1, P2, … (one per row of Parameter Estimates, labelled with its name): rows EST, SE, SIG (of the t test) and DF, then a COV row per parameter; CORB puts CORR rows of correlations there instead. MODEL writes the estimates and their covariance matrix to a JSON file of Statscraft’s own, PARAMETER the estimates alone. JOINTPROB works as in CSDESCRIPTIVES. PRINT GEF writes every estimable function as a combination of free coefficients: a row per parameter and a column per free coefficient L1, L2, … (one per parameter that is not redundant); a redundant parameter’s row says how its coefficient follows from the free ones. Any L that gives every parameter its row’s combination of the free coefficients is estimable, and every estimable L has that form.

Example

CSGLM yield BY soil WITH rainfall /PLAN FILE='farms_plan.json' /STATISTICS PARAMETER SE CINTERVAL DEFF /EMMEANS TABLES=soil COMPARE=soil CONTRAST=REPEATED.

statscraft help CSGLM prints the same text in the terminal. All commands

Statscraft 0.61.0, release v0.61.0

CSLOGISTIC

Binary and multinomial logistic regression on a complex sample, with design-based standard errors and tests.

Syntax

CSLOGISTIC dependent [(LOW | HIGH | value)] [BY factors] [WITH covariates] /PLAN FILE='file'
   [/MODEL effects] [/INTERCEPT [INCLUDE=YES | NO | ONLY] [SHOW=YES | NO]]
   [/CUSTOM [LABEL='text'] [LMATRIX=[c] effect values ... | ALL values; ...] [KMATRIX=k; ...]] ...
   [/ODDSRATIOS FACTOR=[factor[(LOW | HIGH | value)] ...] | COVARIATE=[covariate[(changes)] ...]
                [CONTROL=[factor(LOW | HIGH | value) covariate(MEAN | value) ...]]] ...
   [/CRITERIA [CHKSEP=20] [CILEVEL=95] [DF=n] [LCONVERGE=[0 RELATIVE | ABSOLUTE]] [MXITER=100]
              [MXSTEP=5] [PCONVERGE=[1E-6 RELATIVE | ABSOLUTE]] [SINGULAR=1E-12]]
   [/STATISTICS [PARAMETER] [EXP] [SE] [TTEST] [CINTERVAL] [DEFF] [DEFFSQRT]]
   [/TEST [TYPE=F | ADJF | CHISQUARE | ADJCHISQUARE]
          [PADJUST=LSD | BONFERRONI | SEQBONFERRONI | SIDAK | SEQSIDAK]]
   [/DOMAIN VARIABLE=var(value)] [/MISSING CLASSMISSING=EXCLUDE | INCLUDE]
   [/PRINT [SAMPLEINFO] [VARIABLEINFO] [SUMMARY] [HISTORY[(n)]] [GEF] [LMATRIX] [COVB]
           [CORB] [CLASSTABLE] [NONE]]
   [/SAVE [PREDPROB[(root[:25])]] [PREDVAL[(name)]]]
   [/OUTFILE [COVB='file' | CORB='file'] [MODEL='file' | PARAMETER='file']].

Each category of the dependent variable but the reference one (the highest unless the parentheses say otherwise) gets a logit against the reference with its own set of parameters. The estimates maximize the weighted log likelihood (pseudo-likelihood) by Newton-Raphson with step-halving; they start at 0 with the intercepts at the log ratio of the weighted category counts, and stop when the parameters (PCONVERGE) or the log likelihood (LCONVERGE) change little or after MXITER steps. The covariance is a sandwich: the inverse information on both sides of the design covariance of the score total. Design, df, domains, CUSTOM, TEST and PADJUST work as in CSGLM; a CUSTOM row without ALL is tested for every logit, a row with ALL lists the parameters of all logits in turn. The model summary gives the pseudo R squares of Cox and Snell, Nagelkerke and McFadden from the weighted log likelihoods of the model and of the intercept-only start, with the summed weights as N. ODDSRATIOS compares each level of a factor with its reference, or a covariate moved by each change, with the other variables at CONTROL (factors at their highest level, covariates at their weighted means by default). CLASSTABLE puts each case in its most probable category and sums the weights. Without STATISTICS no parameter table is shown.

OUTFILE works as in CSGLM, the parameters of every logit in turn. JOINTPROB works as in CSDESCRIPTIVES. PRINT GEF works as in CSGLM, with a separate set of free coefficients for every logit.

Example

CSLOGISTIC irrigated (LOW) BY soil WITH rainfall /PLAN FILE='farms_plan.json' /STATISTICS PARAMETER EXP SE CINTERVAL /ODDSRATIOS FACTOR=[soil(LOW)] /PRINT SUMMARY CLASSTABLE.

statscraft help CSLOGISTIC prints the same text in the terminal. All commands

Statscraft 0.61.0, release v0.61.0

CSORDINAL

Ordinal regression (cumulative link model) on a complex sample, with design-based standard errors and tests.

Syntax

CSORDINAL dependent [(ASCENDING | DESCENDING)] [BY factors] [WITH covariates] /PLAN FILE='file'
   [/MODEL effects] [/LINK FUNCTION=LOGIT | PROBIT | CLOGLOG | NLOGLOG | CAUCHIT]
   [/CRITERIA [CHKSEP=20] [CILEVEL=95] [DF=n] [LCONVERGE=[0 RELATIVE | ABSOLUTE]]
              [METHOD=NEWTON | FISHER[(n)]] [MXITER=100] [MXSTEP=5]
              [PCONVERGE=[1E-6 RELATIVE | ABSOLUTE]] [SINGULAR=1E-12]]
   [/STATISTICS [PARAMETER] [EXP] [SE] [TTEST] [CINTERVAL] [DEFF] [DEFFSQRT]]
   [/TEST [TYPE=F | ADJF | CHISQUARE | ADJCHISQUARE]
          [PADJUST=LSD | BONFERRONI | SEQBONFERRONI | SIDAK | SEQSIDAK]]
   [/DOMAIN VARIABLE=var(value)] [/MISSING CLASSMISSING=EXCLUDE | INCLUDE]
   [/PRINT [SAMPLEINFO] [VARIABLEINFO] [SUMMARY] [HISTORY[(n)]] [GEF] [LMATRIX] [COVB]
           [CORB] [CLASSTABLE] [NONE]]
   [/CUSTOM [LABEL='text'] LMATRIX=[thresholds] effect coefficients ... [; ...]
            | ALL coefficients [; ...] [KMATRIX=value [; value ...]]] ...
   [/ODDSRATIOS FACTOR=[factor(LOW | HIGH | value) ...] | COVARIATE=[covariate(changes) ...]
                [CONTROL=[factor(LOW | HIGH | value) covariate(MEAN | value) ...]]] ...
   [/NONPARALLEL [TEST] [PARAMETER] [COVB]]
   [/SAVE [CUMPROB[(root[:n])]] [PREDPROB[(root[:n])]] [PREDVAL[(name)]]
          [PREDVALPROB[(name)]] [OBSVALPROB[(name)]]]
   [/OUTFILE [COVB='file' | CORB='file'] [MODEL='file' | PARAMETER='file']].

The categories of the dependent variable, sorted up (or down with DESCENDING), are ordered 1 to K. For each k below K the model says link(P(Y <= k)) = threshold_k - x’b: one threshold per cut point and one set of coefficients b for all of them, so a positive coefficient moves cases toward the higher categories. LOGIT is the default link. The estimates maximize the weighted log likelihood by Newton-Raphson with step-halving; METHOD=FISHER(n) takes n Fisher scoring steps first (FISHER alone: until convergence), then Newton-Raphson. The start is b = 0 with each threshold at the link of the weighted cumulative share of its category. The covariance is a sandwich: the inverse observed information on both sides of the design covariance of the score total. Design, df, domains and TEST work as in CSGLM; the Tests of Model Effects test the coefficients of each effect (and all of them in the corrected model). The model summary gives the pseudo R squares of Cox and Snell, Nagelkerke and McFadden against the thresholds-only fit, with the summed weights as N. EXP needs the logit link. CLASSTABLE puts each case in its most probable category and sums the weights. Without STATISTICS no parameter table is shown. A CUSTOM row may open with one coefficient per threshold before its effects; ALL takes the thresholds first, then every design column but the intercept. Moving all thresholds together is the same as moving the intercept, so a row is tested only when its coefficients pass as estimable with minus their threshold sum on the intercept: a lone threshold is not testable once there are factors. ODDSRATIOS (logit link only) gives one cumulative odds ratio per comparison, exp(-b’(x1 - x2)), x1 the compared level or the covariate raised by the change; other variables sit at their CONTROL values (factors at the highest level, covariates at the mean by default). NONPARALLEL refits the model with a set of coefficients per threshold, starting from the estimates; TEST is the Wald test that each coefficient is the same for every threshold, PARAMETER and COVB show that model. SAVE writes cumulative and category probabilities, the most probable category and its probability, and the probability of the observed category; a domain case whose dependent is missing still gets predictions when every predictor has a parameter. Default names: CumulativeProbability_k, PredictedProbability_k, PredictedValue, PredictedValueProbability, ObservedValueProbability, with a suffix when taken. OUTFILE works as in CSGLM, thresholds first; the model file also names the link. JOINTPROB works as in CSDESCRIPTIVES. PRINT GEF works as in CSGLM with a free coefficient per threshold first: since moving every threshold moves the intercept, each threshold’s coefficient comes with minus the intercept’s share of the redundant columns.

Example

CSORDINAL rating BY region WITH age /PLAN FILE='poll_plan.json' /LINK FUNCTION=PROBIT /STATISTICS PARAMETER SE CINTERVAL TTEST /PRINT SUMMARY HISTORY.

statscraft help CSORDINAL prints the same text in the terminal. All commands

Statscraft 0.61.0, release v0.61.0

CSCOXREG

Cox proportional hazards regression on a complex sample, with design-based standard errors and tests.

Syntax

CSCOXREG [start] end [BY factors] [WITH covariates]
   /VARIABLES STATUS=var(values) [ID=var] [BASELINESTRATA=var] /PLAN FILE='file'
   [/MODEL effects]
   [/CUSTOM [LABEL='text'] LMATRIX=effect coefficients ... [; ...] [KMATRIX=k [; k ...]]]
   [/CRITERIA [CILEVEL=95] [DF=n] [LCONVERGE=[0 RELATIVE | ABSOLUTE]] [MXITER=100]
              [MXSTEP=5] [PCONVERGE=[1E-6 RELATIVE | ABSOLUTE]] [SINGULAR=1E-12]
              [TIES=EFRON | BRESLOW]]
   [/STATISTICS [PARAMETER] [EXP] [SE] [TTEST] [CINTERVAL] [DEFF] [DEFFSQRT]]
   [/TEST [TYPE=F | ADJF | CHISQUARE | ADJCHISQUARE]
          [PADJUST=LSD | BONFERRONI | SEQBONFERRONI | SIDAK | SEQSIDAK]]
   [/TESTASSUMPTIONS [PROPHAZARD=KM | IDENTITY | LOG | RANK] [PARAMETER] [COVB]]
   [/DOMAIN VARIABLE=var(value)] [/MISSING CLASSMISSING=EXCLUDE | INCLUDE]
   [/PRINT [SAMPLEINFO] [EVENTINFO] [RISKINFO] [HISTORY[(n)]] [GEF] [LMATRIX] [COVB]
           [CORB] [BASELINE] [NONE]]
   [/SURVIVALMETHOD [BASELINE=EFRON | BRESLOW | PRODUCTLIMIT] [CI=ORIGINAL | LOG | LML]]
   [/SAVE keyword[(name)] ... | keyword[(root[:n])] ...]
   [/PLOT [SURVIVAL] [CUMHAZARD] [LML] [OMS] [CI=NO | YES]]
   [/PATTERN [end(times)] var(value or values) ... [BY factor]] [/PATTERN ...]
   [/OUTFILE [COVB='file' | CORB='file'] [MODEL='file'] [SURVIVAL='file']]
   [/JOINTPROB FILE='file' | dataset].

The command fits a Cox proportional hazards model to a complex sample, with design-based standard errors and tests. VARIABLES STATUS and PLAN FILE are required. STATUS lists the event values (values or THRU ranges); any other valid status is censored at the end time. A record is at risk after its start time up to and including its end time, or from the beginning with one time variable. A negative time, or a start time not below the end time, leaves the record out.

The hazard is h0(t) exp(x’b) without an intercept, so the last level of each factor is the reference, and a CUSTOM row must name an effect or ALL (CUSTOM needs LMATRIX). BASELINESTRATA gives each of its values its own baseline hazard with shared coefficients. The estimates maximize the weighted partial likelihood by Newton-Raphson with step-halving from b = 0; tied event times use Efron’s method, or Breslow’s with TIES=BRESLOW. The covariance is a sandwich around the design covariance of the score residuals. Design, df, domains, TEST, CUSTOM and design effects work as in CSGLM, and JOINTPROB as in CSDESCRIPTIVES.

The Model Summary (-2 log pseudo likelihood) and the Tests of Model Effects are always shown. Without PRINT the output also has SAMPLEINFO (the design, with event and censored counts) and EVENTINFO (events and censored records per baseline stratum); a PRINT list replaces these. The parameter table needs STATISTICS. RISKINFO lists the events and records at risk at each event time; GEF has one column per nonredundant parameter.

ID names the subject of each record. A subject’s records are summed before the design variance, and where the plan’s last stage has no clusters the subjects are its units. With ID and one time variable, a subject’s first record starts at the beginning and each later one where the previous record in time ended.

Factors and covariates may come from a TIME PROGRAM: each record is split at the event times of its baseline stratum and the program runs on every piece with T_ set to that event time. Then there are no baseline functions, plots, PATTERN or SURVIVAL file, and SAVE writes only SCHOENFELD, SCORE, DFBETA, their AGG forms and XBETA.

TESTASSUMPTIONS refits with every predictor also multiplied by g(t): one minus the weighted Kaplan-Meier survival (KM, the default), t (IDENTITY), ln(t) (LOG) or the event time’s rank plus one (RANK). A Wald test of the TEST type checks that the extra coefficients are 0; PARAMETER and COVB show the larger model’s estimates and covariances.

Baseline functions are computed per baseline stratum at the reference values (factors at their last level, covariates at their weighted means). The cumulative hazard is Efron’s or Breslow’s sum (as TIES, unless SURVIVALMETHOD BASELINE says otherwise) or minus the log of the product-limit survival, with design-based standard errors. The survival interval is normal on the CI scale: ORIGINAL, LOG (the default) or LML (log of minus log), cut to 0 and 1. PRINT BASELINE tabulates them. PLOT draws them for the reference values and for each PATTERN, whose BY gives one line per factor level; variables a PATTERN leaves out stay at the reference. A PATTERN giving the end time ascending times above 0 is a path: each other variable takes one value or one per time (held up to that time), and the curve stops at the last time.

SAVE writes, for the records analyzed, SCHOENFELD, SCORE and DFBETA (one variable per parameter, root_1, root_2 and so on, at most n, 25 by default), MARTINGALE, DEVIANCE, COXSNELL, XBETA, and SURVIVAL, CUMHAZARD and their LCL_ and UCL_ limits at each record’s own end time and values. Default names are Resid_Schoenfeld, Resid_Score, Resid_DFBETA, Resid_Martingale, Resid_Deviance, Resid_CoxSnell, XBETA, Survival, CumHazard, LCL_Survival and so on, with a suffix when taken. The AGG keywords (default names AggResid_…) total a subject’s records onto its last record; without ID they are skipped with a warning.

OUTFILE COVB or CORB (one of them) writes the matrix file as CSGLM does, MODEL a JSON file with the estimates, covariances, reference values and baseline functions, SURVIVAL a data file of the PLOT curves at every event time.

Example

CSCOXREG months BY clinic WITH dose /VARIABLES STATUS=relapse(1) /PLAN FILE='trial_plan.json' /STATISTICS PARAMETER EXP SE CINTERVAL /PRINT RISKINFO.

statscraft help CSCOXREG prints the same text in the terminal. All commands

Statscraft 0.61.0, release v0.61.0

Macros, files and session

命令功能 {#what-it-does}
DEFINEDefine a macro: a name that stands for syntax, with arguments.
INSERTRun the commands of another syntax file in place of this command.
INCLUDERun the commands of another syntax file, read by the batch rules.
BEGIN PROGRAMA block of code in another programming language; it is skipped with a warning.
SETChange settings of the session.
SHOWShow the current settings.
PRESERVEStore the current settings and folder, to bring them back with RESTORE.
RESTOREBring back the settings and folder the last PRESERVE stored.
CACHEAccepted and has nothing to do: the data are always kept in memory.
CDChange the folder relative file names start from.
PROCEDURE OUTPUTName the file the next procedures write their results to.
FILE HANDLEGive a file or a folder a short name to use in place of its path.
DATASET NAMEGive the active dataset a name, so that it stays open when another one becomes active.
DATASET ACTIVATEMake a named dataset the active one.
DATASET COPYCopy the active dataset, as it is now, into a named dataset.
DATASET DECLAREReserve a dataset name for a dataset that a later command creates.
DATASET CLOSEClose a named dataset, or take the name off the active one.
DATASET DISPLAYList the open datasets.
USESet the historical period of the time series procedures, or use all cases.
DISPLAYShow dictionary information of the active dataset.
LISTList the values of cases.
TITLEPut a title in the output, above the output that follows.
SUBTITLEPut a subtitle in the output, above the output that follows.
ECHOShow a text in the output.
ERASEDelete a file.
PERMISSIONSMake a file read-only, or writeable for its owner.
HOSTRefused: Statscraft never runs operating system commands from syntax.
OUTPUT NEWStart a new output document, which gets the tables from now on.
OUTPUT NAMEName the output document that gets the tables.
OUTPUT ACTIVATESend the tables from now on to an open output document.
OUTPUT CLOSEClose an output document, or all of them.
OUTPUT DISPLAYList the open output documents.
OUTPUT EXPORTWrite the tables and charts of an output document to a workbook, document, presentation, PDF, web page, text or CSV file.
OUTPUT SAVESave an output document as a Statscraft output file (.scout).
OUTPUT OPENOpen a Statscraft output file (.scout) as a new output document.
OUTPUT MODIFYDelete, hide, rename, sort, transpose or reformat items of an output document.
OMSSend the tables, charts and warnings of the commands that follow to a file, or keep them out of the results.
OMSENDEnd OMS requests and the OMS log.
OMSINFOList the OMS requests in force.
OMSLOGKeep a log of when OMS requests start and end and which files they write.
BEGIN CHARTA Statscraft extension: a chart given as JSON goes to the output like a procedure’s chart.
FINISHEnd the job: the commands after it are not read.

All commands

Statscraft 0.61.0, release v0.61.0

DEFINE

Define a macro: a name that stands for syntax, with arguments.

Syntax

DEFINE name ([argument [/ argument ...]])

body !ENDDEFINE.

argument: !POSITIONAL or keyword =, then one of !TOKENS(n), !CHAREND(‘c’), !ENCLOSE(‘a’, ‘b’), !CMDEND, optionally with !DEFAULT(value) and !NOEXPAND (the value is not scanned for macro calls when the expansion is).

DEFINE and !ENDDEFINE are written in full; the name may start with !.

A call is the macro name followed by its arguments, anywhere in a command outside quotes: positional values first, in order, then keyword = value in any order. !TOKENS takes the next n tokens, !CHAREND the tokens up to the character, !ENCLOSE the tokens between the two characters, !CMDEND the rest of the command; the end of the command ends every argument, and an argument left out gets its default or nothing. Tokens no argument takes stay in place.

In the body !1, !2 … are the positional arguments, !* all of them, !name a keyword one.

Outside quotes the body is read in upper case.

Statements: !LET !var = expression; !IF (expression) !THEN … [!ELSE …] !IFEND; !DO !var = from !TO to [!BY step] … !DOEND; !DO !var !IN (list) … !DOEND; !BREAK; !OFFEXPAND and !ONEXPAND to stop and resume expanding macro calls.

Functions: !LENGTH(s) !CONCAT(s, …) !SUBSTR(s, from[, length]) !INDEX(s, part) !HEAD(s) !TAIL(s) !QUOTE(s) !UNQUOTE(s) !UPCASE(s) !BLANKS(n) !NULL !EVAL(s).

Expressions: = <> ~= < > <= >= (or !EQ !NE !LT !GT !LE !GE), !AND !OR !NOT (or & | ~), parentheses. Operands are unquoted and compared as numbers when both are numbers, else as text with case; the result is 1 or 0, and 0 is false.

The expansion is scanned again for macro calls, up to SET MNEST levels (50, at most 100); a !DO loop runs at most SET MITERATE times (1000). One expansion makes at most 100 000 calls and 1 MiB of text. SET MEXPAND=OFF stops expansion and SET MPRINT=YES shows every expanded command. A session (command line or window) keeps the macros and these settings from run to run; DISPLAY MACROS lists the macros.

A body that ends with a period ends the command when the call is the last thing in it; in the middle of a command that period is dropped.

Example

DEFINE !freqs (vars = !CMDEND) FREQUENCIES VARIABLES=!vars. !ENDDEFINE.

statscraft help DEFINE prints the same text in the terminal. All commands

Statscraft 0.61.0, release v0.61.0

INSERT

Run the commands of another syntax file in place of this command.

Syntax

INSERT FILE='path' | handle [SYNTAX=INTERACTIVE | BATCH] [ERROR=CONTINUE | STOP] [CD=NO | YES]
       [ENCODING='name'] [PASSWORD='text'].

A relative path starts from the folder of the file that holds the INSERT, or from the folder CD named. BATCH: a line that starts in the first column starts a new command, and + - or . there is ignored. CD=YES makes the folder of the file the folder for later relative paths. ENCODING names the encoding of the file, such as ‘windows-1257’ or ‘1252’; by default UTF-8 when the file is valid UTF-8, else the system’s legacy code page.

Files nest up to five levels; a file may not insert itself. ERROR and PASSWORD are accepted and have no effect: a run stops at its first error.

Example

INSERT FILE='macros/tables.sps' CD=YES.

statscraft help INSERT prints the same text in the terminal. All commands

Statscraft 0.61.0, release v0.61.0

INCLUDE

Run the commands of another syntax file, read by the batch rules.

Syntax

INCLUDE [FILE=]'path' | handle [ENCODING='name'] [PASSWORD='text'].

Like INSERT SYNTAX=BATCH: a line that starts in the first column starts a new command.

Example

INCLUDE FILE='setup.sps'.

statscraft help INCLUDE prints the same text in the terminal. All commands

Statscraft 0.61.0, release v0.61.0

BEGIN PROGRAM

A block of code in another programming language; it is skipped with a warning.

Syntax

BEGIN PROGRAM [language].

code END PROGRAM.

Statscraft runs no Python or R code. The block is read up to END PROGRAM and not run; the run goes on with one warning per block. Files, variables or commands the block would make are missing, so later commands that need them fail.

Example

BEGIN PROGRAM PYTHON3.
print('not run')
END PROGRAM.

statscraft help BEGIN PROGRAM prints the same text in the terminal. All commands

Statscraft 0.61.0, release v0.61.0

SET

Change settings of the session.

Syntax

SET subcommand[=]value [[/] subcommand[=]value ...].

Followed: FORMAT=Fw.d (format of new numeric variables, default F8.2), DECIMAL=DOT | COMMA (decimal mark of text data read and written by F, E and PCT formats), MPRINT, MEXPAND, MNEST, MITERATE (see DEFINE), LOCALE=‘name’ (sets DECIMAL to the decimal mark of the locale: et_EE, de_DE give COMMA, en_US, en_GB give DOT; OSLOCALE gives DOT; a later DECIMAL overrides it; files are always Unicode, so a code page in the name changes nothing), UNICODE (Statscraft always works in Unicode; OFF has no effect), PRINTBACK, CCA to CCE=‘negative prefix,prefix,suffix,negative suffix’ (custom currency formats; three commas, or three periods when the decimal mark is a comma; ’ before a period or comma makes it text), RNG=MC | MT (the generator of random numbers), SEED=n | RANDOM (starts the MC generator again; a whole number from 1 to 1999999999, default 2000000), MTINDEX=x | RANDOM (starts the MT generator, the Mersenne Twister, again; any number, default 2000000). RANDOM takes the time of day.

MXLOOPS=n: the iterations of a LOOP without an index, and of every loop of MATRIX (default 40). BLANKS=n | SYSMIS: the value of a completely blank numeric field read from text (DATA LIST, GET DATA, NUMBER); it is not made a missing value. EPOCH=year | AUTOMATIC: two-digit years in dates and the DATE. functions fall in the 100 years from that year (AUTOMATIC: from 69 years before the current year). FUZZBITS=n (0 to 20, default 6): the fuzzbits of RND and TRUNC without a third argument. SCALEMIN=n (default 24): a new numeric variable read from text with at least n different values is scale. TVARS=NAMES | LABELS | BOTH: variables in tables as names, labels (default; the name when there is no label) or both, name then label (“q1 Satisfaction”). TNUMBERS=VALUES | LABELS | BOTH: values in tables as values, value labels (default; the value when there is no label) or both, value then label (“1 A great deal”). OVARS and ONUMBERS do the same for the titles of tables.

CTABLES /VLABELS and MULT RESPONSE /FORMAT=NOLABELS win over them. Settings for speed, memory and messages (CACHE, THREADS, WORKSPACE, MXWARNS …) are accepted and have nothing to do. Settings that only change how output looks (TLOOK, WIDTH, LENGTH, DIGITGROUPING …) are accepted with a warning. YES and ON, NO and OFF are the same.

Example

SET FORMAT=F10.3 MPRINT=YES /DECIMAL=DOT TVARS=BOTH TNUMBERS=BOTH.

statscraft help SET prints the same text in the terminal. All commands

Statscraft 0.61.0, release v0.61.0

SHOW

Show the current settings.

Syntax

SHOW [ALL] [setting ...].

Any SET subcommand, and N, WEIGHT, FILTER, SPLIT, DIRECTORY, SYSMIS, VERSION, HANDLES (the file handles), CC (CCA to CCE), ENVIRONMENT, LICENSE, $VARS, SCOMPRESSION, EXTPATHS, PLUGINS, TMSRECORDING, EXTENSIONS and MXMEMORY. SEED shows where the MC generator stands.

A setting Statscraft does not follow shows what Statscraft uses, with a note in a Note column.

Without names: the main settings.

Example

SHOW FORMAT DECIMAL LOCALE.

statscraft help SHOW prints the same text in the terminal. All commands

Statscraft 0.61.0, release v0.61.0

PRESERVE

Store the current settings and folder, to bring them back with RESTORE.

Syntax

PRESERVE.

Stores every setting of SET (CCA to CCE, DECIMAL, FORMAT, LOCALE, MPRINT, MEXPAND, MNEST, MITERATE and the rest) and the folder of CD. PRESERVE and RESTORE nest up to five levels.

A SET subcommand name after PRESERVE (PRESERVE LOCALE, as survey tools write it) is accepted, since every setting is stored anyway; other words are ignored with a warning.

Example

PRESERVE.

statscraft help PRESERVE prints the same text in the terminal. All commands

Statscraft 0.61.0, release v0.61.0

RESTORE

Bring back the settings and folder the last PRESERVE stored.

Syntax

RESTORE.

Every setting and the folder come back as the last PRESERVE stored them; a RESTORE without PRESERVE does nothing, with a warning. After RESTORE LOCALE (or another SET subcommand name) every setting still comes back; a warning names the settings besides LOCALE and DECIMAL that changed after PRESERVE and so come back too. Other words are ignored with a warning.

Example

RESTORE.

statscraft help RESTORE prints the same text in the terminal. All commands

Statscraft 0.61.0, release v0.61.0

CACHE

Accepted and has nothing to do: the data are always kept in memory.

Syntax

CACHE.

Example

CACHE.

statscraft help CACHE prints the same text in the terminal. All commands

Statscraft 0.61.0, release v0.61.0

CD

Change the folder relative file names start from.

Syntax

CD 'folder' | handle.

A relative folder starts from the current one, which is the folder of the syntax file at first. When the last part names no existing folder it is taken as a file name and left out.

Example

CD 'data/2026'.

statscraft help CD prints the same text in the terminal. All commands

Statscraft 0.61.0, release v0.61.0

PROCEDURE OUTPUT

Name the file the next procedures write their results to.

Syntax

PROCEDURE OUTPUT OUTFILE='file' | handle.

CROSSTABS /WRITE puts its cell counts and SURVIVAL /WRITE its life tables in this file. The file stays in effect, for every procedure that asks for it, until another PROCEDURE OUTPUT replaces it. A relative name starts from the current folder (CD).

Example

PROCEDURE OUTPUT OUTFILE='cells.txt'.

statscraft help PROCEDURE OUTPUT prints the same text in the terminal. All commands

Statscraft 0.61.0, release v0.61.0

FILE HANDLE

Give a file or a folder a short name to use in place of its path.

Syntax

FILE HANDLE handle /NAME='path' [/MODE=CHARACTER] [/ENCODING='name'] [/RECFORM=...]
            [/LRECL=n].

Every command that takes a file (GET, SAVE, DATA LIST, GET DATA, MATCH FILES, ADD FILES, APPLY DICTIONARY, AGGREGATE OUTFILE, INSERT, INCLUDE, CD) takes the handle in place of the path, quoted or not; ‘handle/name.sav’ starts from the path of a folder handle. A dataset of the same name comes before a handle. A relative NAME starts from the folder of the last CD. ENCODING is the encoding of a text file read through the handle, when the command gives none. RECFORM and LRECL are ignored with a warning; MODE other than CHARACTER (binary and EBCDIC files) is refused. Handles last for the session.

Example

FILE HANDLE wave2 /NAME='data/2026/wave2.sav'.
GET FILE=wave2.

statscraft help FILE HANDLE prints the same text in the terminal. All commands

Statscraft 0.61.0, release v0.61.0

DATASET NAME

Give the active dataset a name, so that it stays open when another one becomes active.

Syntax

DATASET NAME name [WINDOW=ASIS | FRONT].

A dataset that had the name before is closed. WINDOW is accepted and has no effect.

Example

DATASET NAME survey.

statscraft help DATASET NAME prints the same text in the terminal. All commands

Statscraft 0.61.0, release v0.61.0

DATASET ACTIVATE

Make a named dataset the active one.

Syntax

DATASET ACTIVATE name [WINDOW=ASIS | FRONT].

The dataset that was active stays open when it has a name, else it is closed.

Example

DATASET ACTIVATE survey.

statscraft help DATASET ACTIVATE prints the same text in the terminal. All commands

Statscraft 0.61.0, release v0.61.0

DATASET COPY

Copy the active dataset, as it is now, into a named dataset.

Syntax

DATASET COPY name [WINDOW=MINIMIZED | HIDDEN | FRONT].

A dataset that had the name is replaced, with a warning. When the active dataset has the name, the copy takes it and the active dataset is left without a name.

Example

DATASET COPY men.

statscraft help DATASET COPY prints the same text in the terminal. All commands

Statscraft 0.61.0, release v0.61.0

DATASET DECLARE

Reserve a dataset name for a dataset that a later command creates.

Syntax

DATASET DECLARE name [WINDOW=MINIMIZED | HIDDEN | FRONT].

Example

DATASET DECLARE results.

statscraft help DATASET DECLARE prints the same text in the terminal. All commands

Statscraft 0.61.0, release v0.61.0

DATASET CLOSE

Close a named dataset, or take the name off the active one.

Syntax

DATASET CLOSE name | * | ALL.

The active dataset stays open: closing it, or *, only takes its name off. ALL closes every other dataset.

Example

DATASET CLOSE men.

statscraft help DATASET CLOSE prints the same text in the terminal. All commands

Statscraft 0.61.0, release v0.61.0

DATASET DISPLAY

List the open datasets.

Syntax

DATASET DISPLAY.

Example

DATASET DISPLAY.

statscraft help DATASET DISPLAY prints the same text in the terminal. All commands

Statscraft 0.61.0, release v0.61.0

USE

Set the historical period of the time series procedures, or use all cases.

Syntax

USE ALL.
USE [start] [THRU [end]] [/PERMANENT].

A start or end is a case number or a date written with DATE keywords and values (YEAR 2019 MONTH 3; the highest date variable must be among them); FIRST and LAST mean the ends of the file. The two kinds do not mix. The range acts as a filter for the procedures that follow, while CREATE ignores it and EXSMOOTH and ARIMA estimate on it and forecast after it (see PREDICT). A date start is the first case of that date, a date end the last. ALL or THRU alone uses every case again. USE turns FILTER off; FILTER, SORT CASES and DATE turn USE off. /PERMANENT deletes the cases outside the range.

Example

USE YEAR 2016 THRU YEAR 2021.

statscraft help USE prints the same text in the terminal. All commands

Statscraft 0.61.0, release v0.61.0

DISPLAY

Show dictionary information of the active dataset.

Syntax

DISPLAY [SORTED] [NAMES | INDEX | VARIABLES | LABELS | DICTIONARY | ATTRIBUTES | @ATTRIBUTES
         | SCRATCH | VECTOR | MACROS | DOCUMENTS | FILE LABEL] [/VARIABLES=varlist].

NAMES (the default): names. INDEX: names and positions. VARIABLES: also formats and missing values. LABELS: positions and labels. DICTIONARY: everything, value labels included.

ATTRIBUTES: custom attributes except those starting with @ or $@; @ATTRIBUTES all of them.

MACROS: the names of the macros defined in this run and the runs of the session before, sorted. SORTED sorts by name; /VARIABLES limits the list.

Example

DISPLAY SORTED DICTIONARY /VARIABLES=age TO q5.

statscraft help DISPLAY prints the same text in the terminal. All commands

Statscraft 0.61.0, release v0.61.0

LIST

List the values of cases.

Syntax

LIST [[VARIABLES=]varlist] [/CASES=[FROM n] [TO n] [BY n]] [/FORMAT=[NUMBERED | UNNUMBERED]
     [WRAP | SINGLE]].

Values show in their print format; system-missing is a period. NUMBERED adds the case number. Follows FILTER and SPLIT FILE.

Example

LIST VARIABLES=id age /CASES=FROM 1 TO 10 /FORMAT=NUMBERED.

statscraft help LIST prints the same text in the terminal. All commands

Statscraft 0.61.0, release v0.61.0

TITLE

Put a title in the output, above the output that follows.

Syntax

TITLE [']text['].

Quotes are optional; with them the text may hold the other kind of quote. The title is cut to 60 bytes and shows as a heading where the command stands.

Example

TITLE 'Wave 2: cleaned data'.

statscraft help TITLE prints the same text in the terminal. All commands

Statscraft 0.61.0, release v0.61.0

SUBTITLE

Put a subtitle in the output, above the output that follows.

Syntax

SUBTITLE [']text['].

As TITLE, for a second heading. A blank subtitle (’ ’) shows nothing.

Example

SUBTITLE "Children's shoes only".

statscraft help SUBTITLE prints the same text in the terminal. All commands

Statscraft 0.61.0, release v0.61.0

ECHO

Show a text in the output.

Syntax

ECHO 'text'.

Pieces joined with + show as one line.

Example

ECHO 'Checks done'.

statscraft help ECHO prints the same text in the terminal. All commands

Statscraft 0.61.0, release v0.61.0

ERASE

Delete a file.

Syntax

ERASE FILE [=] 'path'.

One file, named in full; no wildcards. A missing file is an error.

Example

ERASE FILE='old_extract.txt'.

statscraft help ERASE prints the same text in the terminal. All commands

Statscraft 0.61.0, release v0.61.0

PERMISSIONS

Make a file read-only, or writeable for its owner.

Syntax

PERMISSIONS FILE='path' /PERMISSIONS READONLY | WRITEABLE.

READONLY takes the write permission from everyone; WRITEABLE gives it to the owner.

On a file system without such permissions READONLY sets the read-only flag.

Example

PERMISSIONS FILE='final.sav' /PERMISSIONS READONLY.

statscraft help PERMISSIONS prints the same text in the terminal. All commands

Statscraft 0.61.0, release v0.61.0

HOST

Refused: Statscraft never runs operating system commands from syntax.

Syntax

HOST COMMAND=['command' ...] [TIMELIMIT=n].

Read and checked, then refused with an error: a command run from a syntax file could do anything the user can, which makes shared syntax a security risk. Run the commands outside Statscraft, before or after the syntax.

Example

HOST COMMAND=['dir'].

statscraft help HOST prints the same text in the terminal. All commands

Statscraft 0.61.0, release v0.61.0

OUTPUT NEW

Start a new output document, which gets the tables from now on.

Syntax

OUTPUT NEW [NAME=name] [TYPE=VIEWER].

The tables of the commands that follow go to the new document until another one is started or activated. Without NAME it is called Document1, Document2 and so on; a name that another document had passes to the new one, and the other gets a new name. TYPE is ignored. The window shows the tables of every document in its Output view; the documents decide what OUTPUT EXPORT writes. The window session keeps its documents from run to run; a command line run starts without one.

Example

OUTPUT NEW NAME=women.

statscraft help OUTPUT NEW prints the same text in the terminal. All commands

Statscraft 0.61.0, release v0.61.0

OUTPUT NAME

Name the output document that gets the tables.

Syntax

OUTPUT NAME [NAME=]name.

The designated document (the one that gets the tables) takes the name, and a document that had it gets a new one. Without any document yet, an empty one is started.

Example

OUTPUT NAME men.

statscraft help OUTPUT NAME prints the same text in the terminal. All commands

Statscraft 0.61.0, release v0.61.0

OUTPUT ACTIVATE

Send the tables from now on to an open output document.

Syntax

OUTPUT ACTIVATE [NAME=]name.

A name that no open document has gives a warning, and the tables keep going where they went.

Example

OUTPUT ACTIVATE men.

statscraft help OUTPUT ACTIVATE prints the same text in the terminal. All commands

Statscraft 0.61.0, release v0.61.0

OUTPUT CLOSE

Close an output document, or all of them.

Syntax

OUTPUT CLOSE [NAME=]name | * | ALL.

* closes the designated document. Nothing is saved; the next table starts a new document.

A name that no open document has is ignored with a warning.

Example

OUTPUT CLOSE *.

statscraft help OUTPUT CLOSE prints the same text in the terminal. All commands

Statscraft 0.61.0, release v0.61.0

OUTPUT DISPLAY

List the open output documents.

Syntax

OUTPUT DISPLAY.

One row per document with its number of tables; the designated one is marked.

Example

OUTPUT DISPLAY.

statscraft help OUTPUT DISPLAY prints the same text in the terminal. All commands

Statscraft 0.61.0, release v0.61.0

OUTPUT EXPORT

Write the tables and charts of an output document to a workbook, document, presentation, PDF, web page, text or CSV file.

Syntax

OUTPUT EXPORT [NAME=* | name] [/CONTENTS [EXPORT=ALL | VISIBLE] [LAYERS=...] [MODELVIEWS=...]]
   [/XLSX DOCUMENTFILE='path' [OPERATION=CREATEFILE | CREATESHEET | MODIFYSHEET] [SHEET='name']
          [LOCATION=LASTCOLUMN | LASTROW | STARTCELL('B2')] [NOTESCAPTIONS=YES | NO]]
   [/DOC DOCUMENTFILE='path' [NOTESCAPTIONS=YES | NO] [WIDETABLES=...] [PAGESIZE=...]
          [TOPMARGIN=...] [BOTTOMMARGIN=...] [LEFTMARGIN=...] [RIGHTMARGIN=...] [PAGEBREAKS=...]]
   [/PPT DOCUMENTFILE='path' [NOTESCAPTIONS=YES | NO] [SLIDETITLES=YES | NO] [WIDETABLES=...]
          [SLIDESIZE=...] [TOPMARGIN=...] [BOTTOMMARGIN=...] [LEFTMARGIN=...] [RIGHTMARGIN=...]]
   [/PDF DOCUMENTFILE='path' [EMBEDBOOKMARKS=YES | NO] [EMBEDFONTS=YES | NO]]
   [/HTML DOCUMENTFILE='path' [NOTESCAPTIONS=YES | NO] [STYLING=YES | NO]
          [IMAGEFORMAT=JPG | BMP | PNG] [INTERACTIVELAYERS=NO | YES]]
   [/TEXT DOCUMENTFILE='path' [ENCODING=LOCALE | UTF8 | UTF16] [NOTESCAPTIONS=YES | NO]
          [COLUMNWIDTH=AUTOFIT | n] [SEPARATOR=SPACE | TAB] [ROWBORDER='-'] [COLUMNBORDER='|']
          [IMAGEFORMAT=JPG | BMP | EMF | EPS | PNG | TIF]]
   [/CSV DOCUMENTFILE='path' [NOTESCAPTIONS=YES | NO]]
   [/PNG [IMAGEROOT='root'] [PERCENTSIZE=n] [DEPTH=SCREEN | BLACKWHITE | GRAYS256 | ...]]
   [/JPG [IMAGEROOT='root'] [PERCENTSIZE=n] [GRAYSCALE=NO | YES]]
   [/BMP [IMAGEROOT='root'] [PERCENTSIZE=n] [COMPRESS=NO | YES]]
   [/TIF [IMAGEROOT='root'] [PERCENTSIZE=n]] [/EMF ...] [/EPS ...].

Writes the tables and charts that the designated document (NAME=*) or the named one holds so far, in order; an existing file is replaced. Subcommands and keywords are spelled in full.

CONTENTS EXPORT=VISIBLE leaves out what OUTPUT MODIFY hid; every table has one layer, so LAYERS and MODELVIEWS change nothing. NOTESCAPTIONS=NO leaves out the notes under the tables. XLSX puts the tables one below the other on one sheet, named by SHEET or Tables, laid out as the Excel export of the window. CREATESHEET and MODIFYSHEET add to a workbook that OUTPUT EXPORT wrote earlier in the session and that has not changed since; another workbook is refused, so its formulas and formatting cannot be lost. CREATESHEET replaces or adds the sheet; MODIFYSHEET places the tables after the last column or row of the sheet, one column or row apart, or from STARTCELL. A bar, pie, line or area chart goes to the sheet as its data table with an editable chart beside it, drawn in the theme’s colors.

DOC writes a Word document in the .docx format, whatever the file is called: each table under its title, each chart as an editable chart whose numbers Edit Data opens. PPT writes a presentation in the .pptx format with one slide per table or chart; SLIDETITLES=NO leaves the slide titles out, and a chart then shows its own. Page and slide sizes, margins, WIDETABLES and PAGEBREAKS are accepted and not applied. PDF lays the output on A4 portrait pages with 2 cm margins: each command’s heading, then its tables as text you can select, header rows repeated when a table goes on over the next page, the caption below. A table too wide for the page is set smaller, to 70 percent at most; if it still does not fit, its columns come in parts, one below the other, each with the row labels again. Charts are vector drawings.

The TITLE text heads every page and the page number stands at the foot. EMBEDBOOKMARKS=NO leaves out the outline of commands and items; EMBEDFONTS=NO names the font instead of embedding the glyphs used, so a reader without it uses one of its own, and characters outside Windows Latin show as question marks. In DOC, PPT and XLSX, the other charts, such as a histogram or a boxplot, go in as a picture; on a sheet the picture stands beside the data table. HTML writes one web page with every chart in it as a picture, JPG unless IMAGEFORMAT names another; STYLING=NO leaves out the style sheet. TEXT lines the columns up between the borders, or with SEPARATOR=TAB separates the cells by tabs; COLUMNWIDTH=n wraps longer cells; LOCALE and UTF8 write UTF-8, UTF16 writes UTF-16 with a byte order mark. CSV, a Statscraft addition, writes each table as comma-separated values after its title, with a blank line between tables.

TEXT saves each chart as a picture file in the folder of the text, named after the text file with a number from 0 (out.txt gives out0.jpg, out1.jpg, …), and writes the chart’s title and that file name where the chart stands. CSV shows a chart as its data table.

With no document subcommand, each of /PNG, /JPG, /BMP and /TIF saves every chart in its format: IMAGEROOT=‘charts/june’ gives charts/june0.png, charts/june1.png and so on. With a document subcommand IMAGEROOT is not used, and the subcommand of the format in use sets the pictures’ size and colors. PERCENTSIZE (above 0, at most 200) scales a picture: 100 is 1280 pixels wide, the PNG of –charts. GRAYSCALE=YES, DEPTH=GRAYS256 and DEPTH=BLACKWHITE drop the color; the other depths and COMPRESS change nothing. EMF and EPS give a warning, and their charts stay data tables, as does a stem-and-leaf display. /XLS and /XLSM are refused.

Example

OUTPUT EXPORT /XLSX DOCUMENTFILE='results.xlsx' SHEET='Region 1'.

statscraft help OUTPUT EXPORT prints the same text in the terminal. All commands

Statscraft 0.61.0, release v0.61.0

OUTPUT SAVE

Save an output document as a Statscraft output file (.scout).

Syntax

OUTPUT SAVE [NAME=* | name] OUTFILE='path' [TYPE=SPV] [LOCK=NO | YES] [STOREMODEL=YES | NO]
   [/PASSPROTECT PASSWORD=NONE [ENCRYPTEDPW=NO | YES]].

Writes the designated document (NAME=*), or the named one, with every command’s syntax, warnings, tables and charts, as JSON that File > Open, OUTPUT OPEN and any JSON tool read.

A file that exists is replaced; the document stays open and keeps getting tables. An unknown NAME is an error. A path ending in .spv, .spo or .spw (another program’s output files) is written with .scout in its place and a warning, so such a file is never overwritten. TYPE, LOCK and STOREMODEL change nothing. A password on /PASSPROTECT is an error and nothing is saved: Statscraft output files are never encrypted.

Example

OUTPUT SAVE OUTFILE='wave2-results.scout'.

statscraft help OUTPUT SAVE prints the same text in the terminal. All commands

Statscraft 0.61.0, release v0.61.0

OUTPUT OPEN

Open a Statscraft output file (.scout) as a new output document.

Syntax

OUTPUT OPEN FILE='path' [NAME=name] [LOCK=YES | NO] [PASSWORD='text'].

Reads the file into a new document, named by NAME or Document1, Document2 and so on, and sends the tables of the commands that follow to it; OUTPUT SAVE then writes old and new together, and OUTPUT EXPORT converts the file to a workbook, document or web page. A name another document has passes to the new one. A file that is missing, is no Statscraft output file or comes from a newer Statscraft gives a warning, and the tables keep going where they went. For a path ending in .spv, .spo or .spw the .scout file of that name is read. LOCK and PASSWORD change nothing.

Example

OUTPUT OPEN FILE='wave2-results.scout' NAME=wave2.

statscraft help OUTPUT OPEN prints the same text in the terminal. All commands

Statscraft 0.61.0, release v0.61.0

OUTPUT MODIFY

Delete, hide, rename, sort, transpose or reformat items of an output document.

Syntax

OUTPUT MODIFY [NAME=* | ALL | name] [/REPORT PRINTREPORT=NO | YES]
   /SELECT kinds | ALL [EXCEPT (kinds)]
   [/IF [COMMANDS=['name' 'name(n)' 'name(LAST)' LAST]] [SUBTYPES=['title' ...]]
        [LABELS=[EXACT('t') BEGINS('t') ENDS('t') CONTAINS('t')]] [INSTANCES=[n ... LAST]]
        [VISIBLEONLY=NO | YES]]
   [/DELETEOBJECT DELETE=NO | YES]
   [/INDEXING [INDEXTYPE=NUMBER | LETTERLOW | LETTERCAP | ROMANLOW | ROMANCAP] [INDEXSTART=n | 'a']]
   [/OBJECTPROPERTIES [VISIBLE=ASIS | YES | NO] [OUTLINELABEL='text'] [SIZE=...]]
   [/TABLE [TABLETITLE='text'] [TRANSPOSE=NO | YES] [SORT=COLLABEL('label') | COLPOSITION(n)]
        [SORTDIRECTION=ASCENDING | DESCENDING] [TLOOK=...] [SELECTEDLAYER=[...]] [TABLESUMMARY='text'] [PIVOT=[...]]]
   [/TABLECELLS SELECT=['label' POSITION(n) BODY HEADERS TITLE CAPTION FOOTNOTES COUNT MEAN ...]
        [SELECTDIMENSION=BOTH | COLUMNS | ROWS] [SELECTCONDITION=[ALL 'x<0.05' TOP(n) BOTTOM(n)]]
        [APPLYTO=CELL | COLUMN | ROW | COLUMNDATA | ROWDATA | COLUMNHEADER | ROWHEADER]
        [FORMAT=F8.2] [REPLACE='text' | number] [HIDE=NO | YES] [style keywords]]
   [/GRAPHS ...] [/TEXTS [TEXT='text'] ...]
   [/SELECT ... another block].

Works on the items the designated document (or NAME, or ALL documents) holds when it runs.

Each block begins with /SELECT and runs on what the blocks before it left. Kinds: TABLES, CHARTS, HEADINGS and OUTLINEHEADERS (the heading over each command’s items), PAGETITLE (the output of TITLE and SUBTITLE) and UNKNOWN; LOGS, TEXTS, WARNINGS, NOTES, MODELS, TREES and OTHER pick nothing, as Statscraft documents have no such items. /IF keeps the items that meet every condition: COMMANDS names commands as written in the outline, such as ‘Means’, with (n) for the nth run or (LAST); LAST alone is the document’s last command. SUBTYPES match table titles, any case. LABELS test the outline text, case counts. INSTANCES pick the nth item within each command. DELETE=YES removes the items; a heading goes with its command’s items.

VISIBLE=NO hides items: the window and OUTPUT EXPORT with /CONTENTS EXPORT=VISIBLE leave them out, the document and its file keep them. On HEADINGS it hides the heading alone and the tables under it stay; with OUTLINEHEADERS picked as well the command’s items go too. OUTLINELABEL, TABLETITLE and TEXT take )LABEL (the text so far), )INDEX (from INDEXING, else 1, 2, 3), )DATE, )ADATE, )SDATE, )EDATE, )TIME and )ETIME. SORT orders the rows by a column; empty cells go last, rows labelled Total stay, and a table with nested row labels stays as it is. TABLECELLS picks rows or columns by label (any header level) or position, keeps the cells that meet every comparison on x (ABS(x), SYSMIS, numbers or quoted text) and then TOP or BOTTOM, and changes what APPLYTO names: FORMAT changes how numbers show, REPLACE puts in a value, HIDE takes the picked rows or columns out.

Keywords may be shortened to three letters. Fonts, colors, styles, sizes, column widths, table looks, layers, PIVOT, UNGROUP and chart templates change nothing and say so in a warning. PRINTREPORT=YES adds a table of what changed.

Example

OUTPUT MODIFY /SELECT TABLES /IF COMMANDS=['Means'] /TABLE SORT=COLLABEL('Mean')
  SORTDIRECTION=DESCENDING /TABLECELLS SELECT=['Mean'] SELECTDIMENSION=COLUMNS FORMAT=F8.1.

statscraft help OUTPUT MODIFY prints the same text in the terminal. All commands

Statscraft 0.61.0, release v0.61.0

OMS

Send the tables, charts and warnings of the commands that follow to a file, or keep them out of the results.

Syntax

OMS [/SELECT kinds | ALL [EXCEPT=[kinds]]]
   [/IF [COMMANDS=['name' ...]] [SUBTYPES=['title' ...]] [LABELS=['text' ...]] [INSTANCES=[n ... LAST]]]
   [/EXCEPTIF [COMMANDS=[...]] [SUBTYPES=[...]] [LABELS=[...]]]
   /DESTINATION [FORMAT=SAV | HTML | TEXT | TABTEXT | XLSX | DOC | PDF OUTFILE='file' | dataset]
        [VIEWER=YES | NO] [NUMBERED[='name']] [IMAGES=YES | NO] [IMAGEFORMAT=PNG | JPG | BMP] [CHARTSIZE=n]
   [/COLUMNS DIMNAMES=['name' ...] | SEQUENCE=[R1 R2 ... RALL C1 ... CALL]]
   [/TAG='name'] [/NOWARN].

Kinds: TABLES, CHARTS, WARNINGS (the warnings of a command, as one item), TEXTS (the output of ECHO, TITLE and SUBTITLE); HEADINGS, LOGS, MODELS and TREES choose nothing, as Statscraft makes no such items (HTML and PDF show each command’s heading anyway). COMMANDS take names such as ‘Frequencies’ or ‘T-Test’, any case; SUBTYPES take table titles, any case, and the tables of single variables from FREQUENCIES also answer to ‘Frequencies’; LABELS take the outline text, any case. A trailing * matches every text that starts with what comes before it. INSTANCES keep the nth of the matching items of each command. An item must meet every list of /IF, and is left out when it meets every list of /EXCEPTIF. The request lasts until OMSEND, and its file is written again after each command that adds to it. FORMAT=SAV makes a data file of the tables: string variables Command_, Subtype_ and Label_, Var1, Var2, … for the row labels, and one variable per column, named after its header (levels joined by _); a column of numbers is numeric. A table whose number of row labels differs from the earlier tables is left out with a warning. OUTFILE may name a dataset that DATASET DECLARE made. HTML, TEXT, TABTEXT, XLSX, DOC and PDF write as OUTPUT EXPORT does. VIEWER=NO keeps the chosen items out of the results; when several requests choose an item, the latest decides. COLUMNS puts the named row labels (DIMNAMES, by the header of their column) or positions (SEQUENCE) in the columns and the rest in the rows, in the files only. OXML, SPV, XLS, the report formats, XMLWORKSPACE and OUTPUTSET are not written: a warning, and the request only lists in OMSINFO. Keywords that change nothing here, such as IMAGEMAP, give a warning unless NOWARN.

Example

OMS /SELECT TABLES /IF COMMANDS=['Descriptives'] /DESTINATION FORMAT=SAV OUTFILE='stats.sav'
  VIEWER=NO /TAG='desc'.

statscraft help OMS prints the same text in the terminal. All commands

Statscraft 0.61.0, release v0.61.0

OMSEND

End OMS requests and the OMS log.

Syntax

OMSEND [TAG=['name' ...] | TAG=ALL] [FILE=['file' ...]] [LOG].

TAG ends the requests of those names, FILE those that write those files; a name or file that no request has gives a warning. LOG ends the log of OMSLOG. With nothing given, every request and the log end.

Example

OMSEND TAG=['desc'].

statscraft help OMSEND prints the same text in the terminal. All commands

Statscraft 0.61.0, release v0.61.0

OMSINFO

List the OMS requests in force.

Syntax

OMSINFO.

A table with a row per request: its tag, the kinds it chooses, its format, its file and whether the chosen items still show in the results.

Example

OMSINFO.

statscraft help OMSINFO prints the same text in the terminal. All commands

Statscraft 0.61.0, release v0.61.0

OMSLOG

Keep a log of when OMS requests start and end and which files they write.

Syntax

OMSLOG FILE='file' [/APPEND=NO | YES] [/FORMAT=XML | TEXT].

Each event gets a line (TEXT) or an element (XML) with its name, the tag, the file and the time. A later OMSLOG starts a new log; APPEND=YES with TEXT adds to a file that exists.

OMSEND LOG ends the log.

Example

OMSLOG FILE='oms_log.txt' /FORMAT=TEXT.

statscraft help OMSLOG prints the same text in the terminal. All commands

Statscraft 0.61.0, release v0.61.0

BEGIN CHART

A Statscraft extension: a chart given as JSON goes to the output like a procedure’s chart.

Syntax

BEGIN CHART

JSON lines END CHART.

Not a command of the language: Statscraft adds it so that an agent or a script can put a chart that no procedure makes into the designated output document, where it is drawn, saved by OUTPUT SAVE and written by OUTPUT EXPORT like any other. BEGIN CHART and END CHART each stand alone on their line; every line between is JSON, read as it is.

The JSON is either a chart as `statscraft run –json` writes it (a member of charts), optionally with “version”: 1, or a Vega-Lite specification of one view with inline data.values and mark bar, line, area, point or arc, encoded by x, y, color, theta and xOffset or yOffset, without aggregate, bin, timeUnit or transform. Values are taken as they are: a category and series given twice is an error. Fields Statscraft does not know are an error. At most 100 series, 3000 categories, 100000 values and strings of 1000 characters. The MCP tool add_chart and `statscraft chart` write this command.

Example

BEGIN CHART
{"mark": "bar", "data": {"values": [{"region": "North", "sales": 12}, {"region": "South", "sales": 9}]},
 "encoding": {"x": {"field": "region", "type": "nominal"}, "y": {"field": "sales", "type": "quantitative"}}}
END CHART.

statscraft help BEGIN CHART prints the same text in the terminal. All commands

Statscraft 0.61.0, release v0.61.0

FINISH

End the job: the commands after it are not read.

Syntax

FINISH.

The run ends here, as at the end of the syntax. Nothing after FINISH is read, so it causes no error. FINISH in an inserted file ends the whole run; when a range of lines runs, only a FINISH inside it counts. The window and its session stay open.

Example

FREQUENCIES VARIABLES=region.
FINISH.

statscraft help FINISH prints the same text in the terminal. All commands

Statscraft 0.61.0, release v0.61.0

General rules of the language

  A command ends at a line whose last character is a period, at a blank line, or at the end of input.
  Command names and keywords are case-insensitive and may be shortened to three or more letters.
  varlist: variable names, a range written as first TO last, or ALL.
  Strings use single or double quotes; double the quote character to include it. A string may
  run on over line breaks, which it keeps; 'a' + 'b' joins two strings into one.
  Comments: a command starting with * or COMMENT, or /* text */ inside a line.
  Expressions: + - * / **, = <> < > <= >= (or EQ NE LT GT LE GE), AND OR NOT (or & | ~),
  functions such as MEAN(a, b) or SUM(q1 TO q5); LAG(var [, n]) is the value n cases back.
  A function name may be shortened to three or more letters that start no other function.
  An expression nests at most 64 levels of parentheses and functions and holds at most 1500 operators (use SUM(x1 TO x2000) for a longer sum).
  Scratch variables start with #: they begin at 0 or blank, keep their value from case to case,
  are never saved and are gone when the next procedure starts. System variables: $CASENUM
  is the case number, $SYSMIS the system-missing value, $JDATE today as a day count (1 is
  15 October 1582), $DATE and $DATE11 today as dd-mmm-yy and dd-mmm-yyyy text, $TIME now in
  seconds (a date value), $LENGTH and $WIDTH the SET LENGTH and WIDTH.

Functions of expressions (COMPUTE, IF, SELECT IF, DO IF, ELSE IF, LOOP IF, END LOOP IF):
  Arithmetic: ABS RND TRUNC MOD SQRT EXP LN LG10 LNGAMMA SIN COS TAN ARSIN ARCOS ARTAN.
  Statistical, with .n for the valid values needed (MEAN.2): SUM MEAN MEDIAN MIN MAX SD VARIANCE
  CFVAR. Missing values: MISSING SYSMIS VALUE NMISS NVALID. Logical: ANY RANGE. Also LAG and
  VALUELABEL.
  Strings: CONCAT LENGTH CHAR.LENGTH UPCASE LOWER LTRIM RTRIM NTRIM SUBSTR CHAR.SUBSTR INDEX
  CHAR.INDEX RINDEX CHAR.RINDEX LPAD CHAR.LPAD RPAD CHAR.RPAD REPLACE STRUNC CHAR.MBLEN
  MBLEN.BYTE NORMALIZE NUMBER STRING.
  Dates and times: DATE.DMY DATE.MDY DATE.MOYR DATE.QYR DATE.WKYR DATE.YRDAY YRMODA TIME.DAYS
  TIME.HMS CTIME.DAYS CTIME.HOURS CTIME.MINUTES CTIME.SECONDS XDATE.DATE XDATE.HOUR XDATE.JDAY
  XDATE.MDAY XDATE.MINUTE XDATE.MONTH XDATE.QUARTER XDATE.SECOND XDATE.TDAY XDATE.TIME
  XDATE.WEEK XDATE.WKDAY XDATE.YEAR DATEDIFF DATESUM (units years quarters months weeks days
  hours minutes seconds; DATESUM methods 'closest', the default, and 'rollover').
  Distributions: CDFNORM PROBIT, and CDF.d IDF.d PDF.d NCDF.d NPDF.d SIG.d RV.d where the
  distribution d has them: BERNOULLI BETA BINOM BVNOR CAUCHY CHISQ EXP F GAMMA GEOM HALFNRM HYPER
  IGAUSS LAPLACE LNORMAL LOGISTIC NEGBIN NORMAL PARETO POISSON SMOD SRANGE T UNIFORM WEIBULL
  (NCDF and NPDF: BETA CHISQ F T; SIG: CHISQ F). UNIFORM(max), NORMAL(sd) and the RV functions
  draw random numbers. An argument out of range gives system-missing.

All commands

Statscraft 0.61.0, release v0.61.0

命令行帮助

The output of statscraft --help and of --help on every subcommand. The command line explains them with examples.

Statistics workbench

Usage: statscraft <COMMAND>

Commands:
  describe  Show the dictionary and basic counts of a data file or of a session
  run       Run syntax. With --session the dataset, settings and macros are kept between runs
  chart     Add a chart given as JSON to the output: the chart --json writes, or a Vega-Lite specification of a simple view. Runs it as the syntax BEGIN CHART, a Statscraft extension
  check     Validate syntax without saving or writing anything; with --session, against its dataset
  export    Export the output of the running statscraft-gui window to a file, as its File > Export does: the tables and charts of its designated output window
  output    Show what an output window of the running statscraft-gui holds: every command and its tables and charts, which are hidden and which are selected
  undo      Take back the last run that changed the data in the running statscraft-gui window, as its Edit > Undo does; the output stays. Up to 10 runs go back, one per call
  redo      Do again the run that the last undo took back, as Edit > Redo does in the running statscraft-gui window; a new change after the undo ends the redo
  help      Show the syntax of a command, or list all commands
  plan      Lower bounded syntax to an OpenStatSpec transformation plan (JSON), or apply it in a database
  db        Store datasets in an OpenStatSpec database (SQLite, PostgreSQL, MySQL, MariaDB or Dolt) and read them back
  update    Update this installation to the latest published release; --check only checks for one
  mcp       Serve the tools of this program to an AI agent over MCP (standard input and output)
  code      Run a JavaScript async arrow function in code mode, as the MCP tool run_code does: every MCP tool is a function of the object statscraft, with the same arguments, the same default session and the same file sessions as `statscraft mcp`. Prints what the function returns as JSON; console.log lines go to standard error
  connect   Connect Statscraft's MCP server to the AI agents on this computer (Claude, ChatGPT and Codex, Cursor, Copilot, Gemini); --list only shows them, --remove takes it out again

Options:
  -h, --help     Print help
  -V, --version  Print version

statscraft describe

Show the dictionary and basic counts of a data file or of a session

Usage: statscraft describe [OPTIONS] [FILE]

Arguments:
  [FILE]  A .sav or .zsav file

Options:
  -s, --session <SESSION>  Describe this session (dataset, settings, macros) instead of a file; gui is the window
      --json               Print the result as JSON
  -h, --help               Print help

statscraft run

Run syntax. With --session the dataset, settings and macros are kept between runs

Usage: statscraft run [OPTIONS] [FILE]

Arguments:
  [FILE]  Syntax file, or - for standard input

Options:
  -e, --execute <TEXT>               Syntax text given directly
  -s, --session <SESSION>            Session name: the dataset, settings and macros are loaded from and saved to .statscraft/sessions/<name>. The name gui sends the syntax to the running statscraft-gui window instead
      --lines <FIRST-LAST>           Run only the commands inside this inclusive line range, for example 40-55
      --json                         Print tables, charts, changes, warnings and errors as JSON
      --vega-lite                    Also give every chart as a Vega-Lite specification: with --json as its member vega_lite, in Markdown as a code block after the chart's data table
      --encoding <NAME>              Encoding of the syntax file, such as windows-1257 or 1252. Default: UTF-8 when the file is valid UTF-8 (with or without a byte order mark), else the system's legacy code page
      --xlsx <FILE>                  Also write every table and chart of the run to this Excel workbook, one sheet per table; a chart as its data table with an editable chart beside it
      --xlsx-one-sheet               With --xlsx, put all tables on one sheet, one below the other
      --xlsx-no-titles               With --xlsx, leave out the title above each table and chart; labels, captions and what a plugin adds stay, and a sheet is still named after its table
      --plugin <PROGRAM>             With --xlsx, let this plugin program colour, comment and lay out the custom tables, with its settings from the active data's attributes (see docs/plugins.md). Give it more than once for several plugins: they run in that order, and where two style the same thing the later one wins
      --plugin-template <FILE>       With --plugin, a design template file (made by Export in the window's Plugin Settings, see docs/plugins.md): its settings win over the data's attributes, as an active template does in the window. One file per plugin, holding exactly one template of it
      --charts <DIR>                 Also write every chart of the run as a picture into this folder, made if missing: 01-<title>.svg, 02-<title>.svg and so on
      --chart-format <CHART_FORMAT>  With --charts, the picture format [default: svg] [possible values: svg, png]
  -h, --help                         Print help

statscraft chart

Add a chart given as JSON to the output: the chart --json writes, or a Vega-Lite specification of a simple view. Runs it as the syntax BEGIN CHART, a Statscraft extension

Usage: statscraft chart [OPTIONS] <FILE>

Arguments:
  <FILE>  The chart as a JSON file, or - for standard input

Options:
  -s, --session <SESSION>            Session name, as for run; gui adds the chart to the output of the running window
      --json                         Print the result as JSON
      --vega-lite                    Also give the chart as a Vega-Lite specification, as for run
      --xlsx <FILE>                  Also write every table and chart of the run to this Excel workbook, one sheet per table; a chart as its data table with an editable chart beside it
      --xlsx-one-sheet               With --xlsx, put all tables on one sheet, one below the other
      --xlsx-no-titles               With --xlsx, leave out the title above each table and chart; labels, captions and what a plugin adds stay, and a sheet is still named after its table
      --plugin <PROGRAM>             With --xlsx, let this plugin program colour, comment and lay out the custom tables, with its settings from the active data's attributes (see docs/plugins.md). Give it more than once for several plugins: they run in that order, and where two style the same thing the later one wins
      --plugin-template <FILE>       With --plugin, a design template file (made by Export in the window's Plugin Settings, see docs/plugins.md): its settings win over the data's attributes, as an active template does in the window. One file per plugin, holding exactly one template of it
      --charts <DIR>                 Also write every chart of the run as a picture into this folder, made if missing: 01-<title>.svg, 02-<title>.svg and so on
      --chart-format <CHART_FORMAT>  With --charts, the picture format [default: svg] [possible values: svg, png]
  -h, --help                         Print help

statscraft check

Validate syntax without saving or writing anything; with --session, against its dataset

Usage: statscraft check [OPTIONS] [FILE]

Arguments:
  [FILE]  Syntax file, or - for standard input

Options:
  -e, --execute <TEXT>      Syntax text given directly
  -s, --session <SESSION>   Session name: the dataset, settings and macros are loaded from and saved to .statscraft/sessions/<name>. The name gui sends the syntax to the running statscraft-gui window instead
      --lines <FIRST-LAST>  Run only the commands inside this inclusive line range, for example 40-55
      --json                Print tables, charts, changes, warnings and errors as JSON
      --vega-lite           Also give every chart as a Vega-Lite specification: with --json as its member vega_lite, in Markdown as a code block after the chart's data table
      --encoding <NAME>     Encoding of the syntax file, such as windows-1257 or 1252. Default: UTF-8 when the file is valid UTF-8 (with or without a byte order mark), else the system's legacy code page
  -h, --help                Print help

statscraft export

Export the output of the running statscraft-gui window to a file, as its File > Export does: the tables and charts of its designated output window

Usage: statscraft export [OPTIONS] <FILE>

Arguments:
  <FILE>  The file to write: .xlsx, .html or .pdf; a relative path starts in the current folder

Options:
      --format <FORMAT>  xlsx, html or pdf. Default: from the extension of the file
      --one-sheet        Excel: all tables on one sheet, one below the other, instead of one sheet per table
      --selected         Only the tables selected in the output window
      --hidden           Hidden items too
  -h, --help             Print help

statscraft output

Show what an output window of the running statscraft-gui holds: every command and its tables and charts, which are hidden and which are selected

Usage: statscraft output [OPTIONS]

Options:
      --document <DOCUMENT>  The output document; default: the designated output window
      --json                 Print the window's answer as JSON
  -h, --help                 Print help

statscraft undo

Take back the last run that changed the data in the running statscraft-gui window, as its Edit > Undo does; the output stays. Up to 10 runs go back, one per call

Usage: statscraft undo

Options:
  -h, --help  Print help

statscraft redo

Do again the run that the last undo took back, as Edit > Redo does in the running statscraft-gui window; a new change after the undo ends the redo

Usage: statscraft redo

Options:
  -h, --help  Print help

statscraft plan

Lower bounded syntax to an OpenStatSpec transformation plan (JSON), or apply it in a database

Usage: statscraft plan [OPTIONS] [FILE]

Arguments:
  [FILE]  Syntax file, or - for standard input

Options:
  -e, --execute <TEXT>            Syntax text given directly
      --input-schema <FILE>       Input schema: a JSON file with {"variables": [{"name", "storage_kind", ...}]}
  -s, --session <SESSION>         Take the input schema from the dataset of this session
      --sqlite <DB>               OpenStatSpec SQLite database file
      --postgres <URL>            PostgreSQL: postgres://user@host:port/database[?schema=NAME], schema default openstatspec; TLS with &sslmode=verify-full|verify-ca|require and &sslrootcert=CA.pem
      --mysql <URL>               MySQL or MariaDB: mysql://user@host:port/database, a database dedicated to the catalog; TLS with ?ssl-mode=VERIFY_IDENTITY|VERIFY_CA|REQUIRED and &ssl-ca=CA.pem
      --dolt <URL>                Dolt sql-server: mysql://user@host:port/database, a database dedicated to the catalog; TLS as for --mysql
      --name <DATASET>            Dataset name in the database
      --apply                     Apply the plan to the dataset in place
      --expected-branch <BRANCH>  Dolt: the branch the apply must run on
      --expected-head <COMMIT>    Dolt: the commit HEAD must be at
      --actor <ACTOR>             Who applies the plan, for the audit row; defaults to $USER
      --profile <PROFILE>         Frontend profile version [default: 0.3] [possible values: 0.1, 0.2, 0.3]
      --alias <ALIAS>             Symbolic name of the input dataset in the plan [default: input]
  -h, --help                      Print help

Prints one line of canonical JSON: {"ok":true,"plan":...,"plan_hash":...,"source_hash":...}, or {"ok":false,"error":{"code":...,"message":...,"line":...,"column":...},...}. The plan hash is SHA-256 of the canonical plan; the source hash is SHA-256 of the source with line ends converted to LF.

Profile 0.1: RECODE, VARIABLE LABELS, VALUE LABELS.
Profile 0.2 adds COMPUTE target = operand, IF (predicate) target = operand, FORMATS (F only), VARIABLE LEVEL and EXECUTE.
Profile 0.3 adds comments, TO lists, NE <> ~= and NOT, LOWEST/HIGHEST ranges and ADD VALUE LABELS.
Anything else is rejected: this is OpenStatSpec's bounded frontend, not the full language of `statscraft run`.

With --sqlite DB, --postgres URL, --mysql URL or --dolt URL and --name DATASET the input schema comes from that OpenStatSpec dataset, and --apply applies the plan to it in place, in one transaction with one audit row; the output then has "applied":{"apply_id":...,"dataset_id":...,"operation_count":...}. On Dolt, --apply needs --expected-branch and --expected-head: the session must be on that branch at that commit with a clean working set, and the changes stay uncommitted.

statscraft db

Store datasets in an OpenStatSpec database (SQLite, PostgreSQL, MySQL, MariaDB or Dolt) and read them back

Usage: statscraft db <COMMAND>

Commands:
  export        Store a .sav/.zsav file, or the dataset of a session, as a dataset in the database
  import        Read a dataset from the database into a .sav/.zsav file or a session
  capabilities  Print the adapter's capability declaration: versions, limits and atomicity per profile

Options:
  -h, --help  Print help

Prints one line of canonical JSON: {"ok":true,...} or {"ok":false,"error":{"code":...,"message":...}}.

The database is dedicated to OpenStatSpec: a SQLite file, a PostgreSQL schema, or a MySQL, MariaDB or Dolt database. On Dolt, `db export` leaves its changes in the working set and never commits, and `db import` writes nothing at all. Export creates the catalog in a new or empty one and refuses one holding anything else. Each dataset is one table data_<name> with __case_ordinal and one column per variable; the dictionary lives in the catalog tables. A URL without a password takes it from the STATSCRAFT_DB_PASSWORD environment variable; passwords are never printed. Connections are plain TCP unless the URL asks for TLS; TLS always verifies the server certificate against the CA file or the bundled Mozilla roots, and the host name unless the mode is verify-ca.

statscraft db export

Store a .sav/.zsav file, or the dataset of a session, as a dataset in the database

Usage: statscraft db export [OPTIONS] [FILE]

Arguments:
  [FILE]  A .sav or .zsav file

Options:
  -s, --session <SESSION>  Export the dataset of this session instead of a file
      --sqlite <DB>        OpenStatSpec SQLite database file
      --postgres <URL>     PostgreSQL: postgres://user@host:port/database[?schema=NAME], schema default openstatspec; TLS with &sslmode=verify-full|verify-ca|require and &sslrootcert=CA.pem
      --mysql <URL>        MySQL or MariaDB: mysql://user@host:port/database, a database dedicated to the catalog; TLS with ?ssl-mode=VERIFY_IDENTITY|VERIFY_CA|REQUIRED and &ssl-ca=CA.pem
      --dolt <URL>         Dolt sql-server: mysql://user@host:port/database, a database dedicated to the catalog; TLS as for --mysql
      --name <NAME>        Dataset name: ASCII letters, digits and _; defaults to the file or session name
  -h, --help               Print help

statscraft db import

Read a dataset from the database into a .sav/.zsav file or a session

Usage: statscraft db import [OPTIONS] --name <NAME>

Options:
      --sqlite <DB>        OpenStatSpec SQLite database file
      --postgres <URL>     PostgreSQL: postgres://user@host:port/database[?schema=NAME], schema default openstatspec; TLS with &sslmode=verify-full|verify-ca|require and &sslrootcert=CA.pem
      --mysql <URL>        MySQL or MariaDB: mysql://user@host:port/database, a database dedicated to the catalog; TLS with ?ssl-mode=VERIFY_IDENTITY|VERIFY_CA|REQUIRED and &ssl-ca=CA.pem
      --dolt <URL>         Dolt sql-server: mysql://user@host:port/database, a database dedicated to the catalog; TLS as for --mysql
      --name <NAME>        Dataset name
      --out <FILE>         Write this .sav or .zsav file
  -s, --session <SESSION>  Make the dataset the one of this session instead
      --allow-loss         Go on when the catalog holds items the dataset cannot keep, and record each loss
  -h, --help               Print help

statscraft db capabilities

Print the adapter's capability declaration: versions, limits and atomicity per profile

Usage: statscraft db capabilities

Options:
  -h, --help  Print help

statscraft update

Update this installation to the latest published release; --check only checks for one

Usage: statscraft update [OPTIONS]

Options:
      --check            Only check: exit code 0 when up to date, 10 when a newer release exists
      --json             With --check, print the result as JSON
      --plugin <PLUGIN>  With --check, check this plugin program for a newer version instead; it never installs one (the window's Edit > Settings > Plugins does that)
  -h, --help             Print help

statscraft mcp

Serve the tools of this program to an AI agent over MCP (standard input and output)

Usage: statscraft mcp

Options:
  -h, --help  Print help

statscraft code

Run a JavaScript async arrow function in code mode, as the MCP tool run_code does: every MCP tool is a function of the object statscraft, with the same arguments, the same default session and the same file sessions as `statscraft mcp`. Prints what the function returns as JSON; console.log lines go to standard error

Usage: statscraft code [OPTIONS] <FILE>

Arguments:
  <FILE>  The script file, or - for standard input

Options:
      --json  Print ok, value, logs and error as JSON instead of the value alone
  -h, --help  Print help

statscraft connect

Connect Statscraft's MCP server to the AI agents on this computer (Claude, ChatGPT and Codex, Cursor, Copilot, Gemini); --list only shows them, --remove takes it out again

Usage: statscraft connect [OPTIONS] [CLIENT]

Arguments:
  [CLIENT]  The agent: claude-desktop, claude-code, codex (also the Codex view of the ChatGPT app), cursor, copilot (VS Code), gemini or antigravity. On Windows, the agents inside WSL as --list names them, such as codex-wsl:Ubuntu. Default: every agent found on this computer

Options:
      --remove  Take Statscraft out of the agent's settings (every agent when none is named)
      --list    Only show which agents are installed and connected; change nothing
      --json    Print the result as JSON
  -h, --help    Print help

Statscraft 0.61.0, release v0.61.0

更新日志

0.61.0 (2026-12-03)

The first release with signed Windows files: Windows names Kood kolm OÜ as the publisher instead of an unknown one. It also brings unit-independent results for more models and several CTABLES fixes.

  • The Windows installer, its uninstaller and both programs in the installer and the .zip are signed by Kood kolm OÜ. An installed earlier version needs no uninstalling: the new installer installs over it.
  • LOGISTIC REGRESSION, ARIMA, TSMODEL (ARIMA with regressors), NLR, CNLR and GENLOG (cell covariates) no longer depend on the units of a covariate: a covariate in millions gives the same score tests, estimates and standard errors as the same covariate in units.
  • CTABLES keeps a TOTALN, or a percentage of it, that is above zero when FORMAT EMPTY blanks the empty cells, shows MEAN.SE and SUM.SE for a cell whose weight is between 1 and 1.5, and takes a category as empty (EMPTY=EXCLUDE) when only cases without weight fall in it.
  • CTABLES CATEGORIES KEY=LABEL puts values without a label after the labelled ones in both orders, and the chi-square test and the column proportion test leave out a table whose rows and columns are one variable or, with weights, a table without weighted counts or weighted row or column percentages, with the reason in the note.

0.60.0 (2026-12-02)

A correctness release for the regression and mixed models: results no longer depend on the units a covariate is measured in, and values that cannot be computed are left empty with a warning instead of showing 0, NaN or a misleading test.

  • GENLIN, NOMREG, PLUM, COXREG, MIXED and the complex samples regressions (CSLOGISTIC and others) keep every term, standard error and joint test when a covariate is in large or small units, such as amounts in millions, and no longer stop after one iteration.
  • MIXED and GENLINMIXED keep each random-effects covariance matrix valid, and a variance that rests at 0 empties only its own standard error, with a warning that names it; AICC is empty when there are too few cases for it.
  • GENLIN finds complete and quasi-complete separation from CRITERIA CHECKSEP on, and a Lagrange test or goodness-of-fit df that cannot be computed is empty with a warning.
  • GENLINMIXED fits a count target that is linear in the predictors, sums COVB=ROBUST over the DATA_STRUCTURE subjects, and takes the target’s categories only from the cases the model uses.
  • A .sav file with NaN or infinite numbers opens with a warning, and FREQUENCIES and CODEBOOK count such values as system-missing; -0 shows as 0 and is the same category as 0.

0.59.0 (2026-12-02)

GLM and UNIANOVA give more reliable Type III and IV tests when a covariate overlaps a factor, GLM /RANDOM handles error terms more carefully, and GENLOG now stops with a clear error when all weights are 0.

  • GLM and UNIANOVA keep Type III and IV tests scale-invariant when a covariate is collinear with a factor, and GLM /RANDOM scales its error-term solver for large weights and never places a random effect’s own mean square in its error denominator.
  • GENLOG stops with an error when every case has a weight of 0, instead of fitting a model to empty cells.

0.58.0 (2026-12-02)

Agents get a code mode: one call runs a short JavaScript function that uses the MCP tools, so several steps take one round trip.

  • Code mode for agents: the MCP tool run_code and statscraft code run a JavaScript function in which every MCP tool is a function, so an agent runs several steps in one call, decides from the results and returns only the numbers it needs. See Code mode.

0.57.0 (2026-12-01)

The multiple response sets dialog shows the sets already defined, and data in an OpenStatSpec database can be read with GET DATA and changed in place from the MCP server.

  • Data > Define Multiple Response Sets… now lists the sets already in the dataset under the form, with their type, label and variables, and lets you load any of them into the form to edit.
  • GET DATA /TYPE=OPENSTATSPEC reads a dataset of an OpenStatSpec database (SQLite, PostgreSQL, MySQL or MariaDB, Dolt) as the active dataset, from run, the window and the MCP server. The password comes from STATSCRAFT_DB_PASSWORD, never from the syntax.
  • MCP: apply_plan previews or applies an OpenStatSpec transformation plan in place to a dataset in a database, as statscraft plan --apply does, in one transaction with an audit row.
  • The OpenStatSpec driver follows specification v0.6.0 with its Conformance Supplement 0.6.

0.56.0 (2026-12-01)

A small release: CROSSTABS gets Monte Carlo and exact significance for more measures, and several procedures say plainly when a request cannot apply.

  • CROSSTABS /METHOD=MC now gives a Monte Carlo significance for gamma, the symmetric lambda and the McNemar-Bowker test, and /METHOD=EXACT an exact one for McNemar-Bowker.
  • FREQUENCIES, CODEBOOK, SUMMARIZE and MEANS warn, naming the variable, when a string variable is asked for statistics it cannot have.
  • ROC honors only the last of a subcommand given twice, warns about it and about contradicting keywords in one subcommand.
  • SURVIVAL warns when no case is left for a table.

0.55.0 (2026-11-30)

A review of the procedures against the manual corrects results and edge cases in regression, factor analysis, crosstabs and the descriptive procedures, and GLM and KNN run faster.

  • REGRESSION, LOGISTIC REGRESSION and FACTOR give the right values in perfect fits, under regression weights and with covariance matrices, and step without a hidden limit.
  • CROSSTABS, DESCRIPTIVES, FREQUENCIES, MEANS and EXAMINE take their subcommands in any order and handle empty rows, large weights and missing values as the manual says; RELIABILITY works from the covariance matrix.
  • GLM, UNIANOVA and REGRESSION compute about twice as fast on large models, and KNN with a range of neighbors finds them once.
  • A number typed or pasted into a cell may carry thousands marks (1,234,567), and the dialogs offer only the options that apply, such as the post hoc tests for unequal variances with one factor.
  • The empty window says how to start, and two updates running at once no longer share a download folder.

0.54.0 (2026-11-29)

The Data View takes pasted cells, a fill handle and value filters, the window speaks three more languages, a decimal comma works everywhere, and large files open, read, save and run with far less memory and time.

  • The Data View pastes tab-separated cells (Ctrl+V and the right-click menus), has a fill handle that repeats cells or continues a series, Filter by values… on a column, Change to numeric for a text column of plain numbers, and scrolls when a drag passes its edge.
  • The window also speaks Brazilian Portuguese, German and French.
  • SET DECIMAL=COMMA shows and takes a decimal comma in the data window, in the tables of every command and their exports, and in DATA LIST, GET DATA, NUMBER, STRING and WRITE.
  • Large files take far less memory and time: opening compressed .sav files, reading text with GET DATA, SAVE TRANSLATE, .zsav saving, VARSTOCASES, cell edits, long syntax files, hierarchical CLUSTER (3,000 cases in under a second instead of 24) and KNN (20,000 cases in under half a second instead of 60).
  • New: KEYED DATA LIST, VERIFY, GENLIN Tweedie and ordinal /REPEATED, and the Waller-Duncan test in ONEWAY.

0.53.0 (2026-11-26)

The window starts new data and takes new variables and cases where you type them, CATPCA gives bootstrap intervals and confidence ellipses, and SAVE CODEPAGE writes data files in a code page.

  • File > New > Data opens an empty data window. A name typed in the empty row under the last variable of the Variables tab makes a new numeric variable, and a value typed in the empty row under the last case of the Data tab adds a case (ADD CASE, a Statscraft extension). NUMERIC and STRING after NEW FILE start the blank dataset.
  • CATPCA /RESAMPLE=BOOTSTRAP analyses balanced or unbalanced bootstrap samples of the cases, turned to the data’s solution by a Procrustes rotation, with percentile intervals for the eigenvalues, loadings and category values, interval bands on the transformation plots and, for two dimensions, confidence ellipses (LDELLAREA, OBELLAREA, CTELLAREA, NELLPNT); /SAVE saves the ellipse areas and /OUTFILE takes ELLCOORD for their coordinates.
  • SAVE CODEPAGE writes a data file whose text (names, labels, string values, notes) is in a code page of your choice, such as '1252' or 'windows-1257', with KEEP, DROP and UNSELECTED.
  • ALSCAL /FILE takes (FIXED) after CONFIG, ROWCONF, COLCONF, SUBJWGHT and STIMWGHT: those coordinates and weights stay as the file gives them and the rest is solved for them.

0.52.0 (2026-11-26)

ALSCAL scales asymmetric and rectangular data with all its models, PLS saves its datasets under SPLIT FILE, and TWOSTEP CLUSTER updates a saved model.

  • ALSCAL takes /SHAPE=ASYMMETRIC and RECTANGULAR (unfolding, with /INPUT=ROWS(n)), /CONDITION=ROW, and the models ASCAL, AINDS (stimulus weights) and GEMSCAL (a metric of its own for every matrix, with /CRITERIA=DIRECTIONS(q)).
  • PLS /OUTDATASET works under SPLIT FILE: every group is fitted and the CASES, LATENTFACTORS and PREDICTORS datasets hold the groups one after the other, the split variables in front.
  • TWOSTEP CLUSTER /INFILE updates a model saved with /OUTFILE STATE: the saved subclusters and the cases of the active file go into the tree together, with the saved distance, standardization and limits.

0.51.0 (2026-11-26)

LOGLINEAR fits general loglinear and logit models, SAVE TRANSLATE writes SAS transport and dBASE files, and stacked plugin tables line up their columns on one Excel sheet.

  • Excel export on one sheet: tables in a plugin’s stacked layout line up their data columns, so the total of a means table stands under the total of the percentage tables.
  • SAVE TRANSLATE writes SAS transport files with /TYPE=SAS /VERSION=X: labels, date, time and datetime formats, and one missing value.
  • SAVE TRANSLATE writes dBASE III and IV files with /TYPE=DB3 and /TYPE=DB4: fields from the print formats, dates as date fields, a missing number as asterisks.
  • LOGLINEAR fits general loglinear and logit models of a table of counts with contrasts for every factor (DEVIATION, SIMPLE, DIFFERENCE, HELMERT, REPEATED, POLYNOMIAL, SPECIAL and BASIS SPECIAL), cell covariates, cell weights and structural zeros, several DESIGNs with settings that carry over, and generalized residuals: cell counts with raw, standardized and adjusted residuals, the likelihood-ratio and Pearson tests, the design matrix, parameter estimates with z values and intervals and their correlation, the analysis of dispersion for a logit model, and residual plots.
  • GRAPH accepts /TEMPLATE: it is read and ignored with a note, since charts come as data.
  • CLUSTER /SAVE works with /MATRIX=IN: the matrix of the active dataset’s cases gives the membership variables.

0.50.0 (2026-11-26)

Nonlinear regression arrives with NLR and CNLR, the time series commands gain RMV, FIT and SHIFT VALUES, MCONVERT converts matrix data, and the window speaks Spanish.

  • The window speaks Spanish: Edit > Settings > Language chooses System (the default, Spanish when the computer is set to Spanish), English or Español, and the change applies at once. The menus, toolbars, status bar, grids, the Settings dialog and the buttons of the dialogs follow it; syntax, output tables and command messages stay the same in every language. See The language of the window.
  • The README is also in Spanish and Simplified Chinese.
  • RMV copies series with their missing values filled in: LINT interpolates, MEAN and MEDIAN use the nearest valid values on each side, SMEAN the series mean and TREND a fitted line.
  • NLR fits nonlinear models by least squares (Levenberg-Marquardt) to the model that MODEL PROGRAM and DERIVATIVES define: iteration history, analysis of variance with R squared, estimates with asymptotic standard errors and 95% intervals, parameter correlations, FILE and OUTFILE for starting values, SAVE of predicted values, residuals and derivatives, and a check of the derivatives given against numerical ones. CLEAR MODEL PROGRAMS drops the programs.
  • SHIFT VALUES adds a variable holding the value of another variable from an earlier or later case, within each split group, with the dictionary entry of the original.
  • MCONVERT turns matrix data of covariances into correlations with standard deviations, and back, set by set, in the active dataset or a file.
  • FIT gives goodness-of-fit statistics of residual series from the time series commands: mean, absolute and squared errors, the Durbin-Watson statistic, percent errors against the observed series, and separate columns for a PREDICT period inside the series.
  • CNLR fits the same model under constraints: simple bounds, linear constraints and bounds on CONSTRAINED FUNCTIONS computed from the parameters, with an optional LOSS function to minimize instead of the squared residuals and BOOTSTRAP for standard errors, correlations and 95% trimmed ranges. It gives the iteration history and, for squared residuals, the tables of NLR; FILE, OUTFILE and SAVE work as in NLR.

0.49.0 (2026-11-25)

GRAPH draws grouped high-low charts, MVA writes its filled data under SPLIT FILE, CURVEFIT can apply an earlier fit as it is, and INCLUDE keeps inline data intact.

  • MVA writes its OUTFILE under SPLIT FILE: each group is filled from its own estimates, all in one file.
  • GRAPH /HILO draws grouped high-low and high-low-close charts: with more than three series, each group of two or three stands beside the next in a category.
  • INCLUDE reads the inline data of a file as it is: a data line that starts with a minus sign or a period keeps it, and fixed-format records no longer get a blank record between them.
  • CURVEFIT /APPLY FIT keeps the estimates of the earlier fit: the tables are the original ones, and the plot and the saved variables put its coefficients to use on the current data.

0.48.0 (2026-11-25)

GGRAPH draws error bars, and plugin presets can be corrected in place.

  • GGRAPH reads the interval functions MEANCI, MEDIANCI, MEANSD, MEANSE and COUNTCI: each gives a value and its high and low end, VARSTOCASES takes them in HIGH and LOW columns, and an interval(position(region.spread.range(x*(low+high)))) element draws them as error bars around the other element.
  • Plugin Settings: choose a preset, change its value or name and click Save to keep the change in that preset.
  • Whole numbers in the plugin settings show without a decimal point, for example a population of 1300000.
  • Style samples are black on white as in Excel, whatever the window’s theme.

0.47.0 (2026-11-25)

The syntax editor finds and replaces text.

  • The syntax editor finds and replaces text: Ctrl+F opens a find bar and Ctrl+H a replace row, with Match case, Whole word, F3 for the next match and Replace all. See the window.

0.46.0 (2026-11-25)

Expressions read today’s date and the page size, GLM names its saved variables per dependent variable, and MANOVA shows the decomposition and collinearity of its design.

  • MANOVA /PRINT=DESIGN(DECOMP) shows the triangular decomposition of the design and DESIGN(COLLINEARITY) its collinearity diagnostics.
  • GLM /SAVE names the new variable of each dependent variable, for example PRED(p1 p2), also in the multivariate and repeated measures models.
  • Expressions read the system variables $JDATE, $DATE, $DATE11 and $TIME (today and now) and $LENGTH and $WIDTH (the SET page size).

0.45.0 (2026-11-25)

UNIANOVA and GLM write their effects table as a data file, APPLY can repeat any earlier model of the session, and GGRAPH computes the percentile of grouped values.

  • GGRAPH and XGRAPH compute GPTILE, the percentile of grouped values.
  • APPLY 'MOD_2' repeats any earlier model of the session, not only the previous one: ACF, PACF, CCF, SEASON, EXSMOOTH, ARIMA, AREG, SPECTRA, 2SLS, TSPLOT, CASEPLOT, CURVEFIT, WLS and PPLOT number their models MOD_1, MOD_2, … in the order the session runs them.
  • UNIANOVA and GLM write the Tests of Between-Subjects Effects as a data file with /OUTFILE EFFECT.

0.44.0 (2026-11-25)

COXREG writes its coefficients and survival tables to files, and the robust covariance file of GLM holds the diagonal only again.

  • COXREG writes the coefficients of the final model and the survival table of every stratum (at the baseline, at the means and for each PATTERN line) with /OUTFILE COEFF and TABLE.
  • UNIANOVA and GLM: the file of /OUTFILE HCCOVB holds the diagonal terms of the robust covariance matrix only, blank off the diagonal (0.43.0 wrote the whole matrix).

0.43.0 (2026-11-25)

UNIANOVA and GLM save their robust covariance matrix, and a plugin setting can hold for every data file.

  • UNIANOVA and GLM write the robust covariance matrix of /ROBUST with /OUTFILE HCCOVB.
  • A plugin setting can hold for every data file: the window keeps the last value chosen on the computer, also with no data open, and marks it (all data files) in Plugin Settings.

0.42.0 (2026-11-25)

AUTORECODE keeps its codes from file to file, ALTER TYPE reads more string formats, and ALSCAL can start from a saved configuration.

  • AUTORECODE saves its scheme to a template file (/SAVE TEMPLATE) and applies one (/APPLY TEMPLATE), so another file is recoded with the same codes and its new values get the next ones.
  • ALTER TYPE turns a string into a date (DATE, ADATE, EDATE, SDATE) or a number in the E, DOLLAR, PCT and N formats, as well as F, COMMA and DOT.
  • ALSCAL /FILE starts the iterations from the coordinates (and, for INDSCAL, the subject weights) of a configuration file, such as the one its own OUTFILE writes.
  • ONEWAY, PPLOT and SPCHART accept /TEMPLATE and ignore it with a note, as the other commands with charts do, so scripts that name a chart template run.

0.41.0 (2026-11-25)

More procedures write their parameter matrices to a file or dataset, and two more commands repeat with /APPLY.

  • REGRESSION writes the covariance (/OUTFILE COVB) or correlation (CORB) matrix of the coefficients of its last equation, with the estimates, standard errors, significances and degrees of freedom, to a file or dataset.
  • UNIANOVA and GLM with one dependent variable write the parameter covariance matrix (/OUTFILE COVB), their correlation matrix (CORB) and the design matrix (DESIGN) to files or datasets.
  • GENLIN writes the covariance or correlation matrix of its parameters, with the estimates, standard errors, significances and degrees of freedom, to a file or dataset (/OUTFILE COVB= or CORB=), and /CRITERIA INITIAL= reads start values from such a file or dataset, group by group under SPLIT FILE.
  • STRING also writes the custom currency formats CCA to CCE, as SET defines them.
  • CURVEFIT and WLS take /APPLY: the previous command’s specifications run again on the same or new variables, with the changes the new command gives.

0.40.0 (2026-11-25)

DISCRIMINANT can work from a matrix file instead of the cases.

  • DISCRIMINANT /MATRIX=IN reads the group counts, means and pooled deviations and correlations of a matrix file: with IN(*) the analysis is made from the matrix alone, with a file or dataset name the cases of the active dataset are classified by it.
  • DISCRIMINANT /MATRIX=OUT writes each group’s own deviations and correlations when BOXM, GCOV or CLASSIFY=SEPARATE is given, and /MATRIX=IN reads them back.

0.39.0 (2026-11-25)

Case influence in TREE works with every dependent in CHAID and CRT.

  • TREE /INFLUENCE also works with CRT and a nominal or ordinal dependent.
  • TREE /INFLUENCE also works with a scale dependent, in CHAID and in CRT.

0.38.1 (2026-11-25)

Two fixes to CHAID trees.

  • TREE: exhaustive CHAID no longer stops with an error when an ordinal predictor has only its missing category in a node.
  • TREE /INFLUENCE: the risk of a CHAID tree is the share of the cases (their frequencies) that the tree misclassifies, as without an influence.

0.38.0 (2026-11-24)

CHAID trees can split merged categories again and weigh cases by their influence.

  • TREE /CHAID SPLITMERGED=YES: a merged group of three or more categories is split again where that split is significant at ALPHAMERGE.
  • TREE /INFLUENCE: with CHAID and a nominal or ordinal dependent, each case counts in growing the tree by the value of an influence variable.

0.37.0 (2026-11-24)

TREE finds the nodes that answer best for a target category.

  • TREE /TARGETRESPONSE: for each target category, the terminal nodes ranked by their response rate, with the rule that leads to each, the cumulative response and whether it reaches a minimum rate you set, and a chart of the cumulative response.

0.36.0 (2026-11-23)

Plugins lay out tables of means more compactly and can offer their settings as a list.

  • In a plugin’s compact layout, a table of means shows each question in its mean row, with no row of its own above it, in Excel and on web pages.
  • A plugin setting can offer a fixed set of values, chosen from a list in the plugin’s settings.

0.35.0 (2026-11-23)

Undo and redo go more than one step.

  • Undo goes back more than one change: Edit > Undo takes back up to the last 10 runs that changed the data, one at a time, and the data file that was open comes back with them. New Edit > Redo (Ctrl+Y or Ctrl+Shift+Z) does a run again; a new change ends the redo. Both menu items name the run they act on. statscraft redo and the MCP tool redo do the same as Edit > Redo, and undo in both goes one change further back on each call.

0.34.0 (2026-11-23)

The command pages are easier to use: even in length, with examples on the sample file and their output.

  • The 20 most used commands, such as FREQUENCIES, CTABLES and COMPUTE, have examples on survey.sav with the table they give.
  • TREE describes all four growing methods: CHAID, exhaustive CHAID, CRT and QUEST.
  • Completion in the syntax editor offers a function with its parenthesis inside an expression.

0.33.0 (2026-11-23)

The documentation is rewritten for users, with a sample file to follow along.

  • Getting started goes from installing to an Excel workbook with a custom table, in the window, on the sample file survey.sav.
  • The window guide lists every menu item with the command it runs, and explains custom tables step by step.
  • MANOVA draws boxplots, cell plots, normal plots, predicted means and residual plots.

0.32.0 (2026-11-23)

MANOVA can now save its cell statistics to a matrix file and run from one, and the help and documentation are easier to read.

  • MANOVA /MATRIX writes cell counts, means and pooled correlations to a matrix file, and runs an analysis from such a file or from a CORRELATIONS matrix.
  • MANOVA /ANALYSIS runs several groups of analyses in one command, also with repeated measures.
  • The help and the command pages describe only what Statscraft does and are easier to read on the documentation site.

0.31.0 (2026-11-23)

Multidimensional scaling with PROXSCAL can now be tied to outside variables or fixed coordinates, and repeated measures in GLM get profile plots.

  • PROXSCAL can build the common space from independent variables, or hold chosen coordinates fixed.
  • PROXSCAL can start from coordinates in a file and plots how the independent variables correlate with the dimensions.
  • GLM draws profile plots of estimated marginal means for repeated measures designs.
  • SURVIVAL can write its life tables to a file.

0.30.0 (2026-11-23)

Classification trees can now weigh costs and profits, check themselves on held-out data, and write their rules as syntax or SQL. GLM repeated measures gets the full set of tests and saved values.

  • TREE writes the tree as rules: syntax you can run, SQL, or plain sentences.
  • TREE takes misclassification costs, profits and adjusted priors, and validates a tree by split sample or cross-validation.
  • TREE CHAID handles a scale dependent, and gain tables come by percentile as well as by node.
  • GLM with repeated measures takes EMMEANS, POSTHOC, contrasts, custom hypotheses, SAVE and the extra printed tables.
  • GENLIN gives score tests with repeated measures, GENLINMIXED fits fixed effects alone, and ADP can build new predictors from correlated inputs.

0.29.0 (2026-11-23)

TREE grows QUEST trees, GLM fits several measures over one repeated measures design, and post hoc tests are faster and more accurate.

  • TREE /METHOD TYPE=QUEST grows binary trees for a nominal dependent.
  • GLM /MEASURE fits doubly multivariate repeated measures.
  • Post hoc tests in ONEWAY, UNIANOVA and GLM run 10 to 40 times faster, and their critical values are now accurate with very few degrees of freedom.
  • NPAR TESTS says at once when an exact test would take too long, and the exact tests that fit run faster.

0.28.0 (2026-11-22)

TREE grows CRT trees, UNIANOVA and GLM take random factors, and more procedures write matrix files.

  • TREE CRT grows binary trees for categorical or scale dependents, with priors, surrogate splits, pruning and predictor importance.
  • UNIANOVA and GLM /RANDOM handle random factors, testing each effect against the right error term; the Univariate dialog offers them.
  • FACTOR, DISCRIMINANT and CLUSTER write matrix files, and FACTOR reads a loading matrix.
  • GENLIN gives profile likelihood intervals for the scale and the negative binomial parameter.
  • NPAR TESTS gives the exact significance of the marginal homogeneity test.

0.27.0 (2026-11-22)

Correlations get confidence intervals, GENLIN gets profile likelihood intervals, more nonparametric tests are exact, and GLM tests for heteroskedasticity. The dialogs offer all of these.

  • CORRELATIONS and NONPAR CORR give confidence intervals for each coefficient and write matrix files.
  • GENLIN gives profile likelihood intervals and takes starting values.
  • NPAR TESTS gives exact significances for the two-sample Kolmogorov-Smirnov, median, Kruskal-Wallis, Jonckheere-Terpstra, Friedman, Kendall’s W and Cochran tests.
  • FACTOR analyzes the covariance matrix and writes matrix files; DISCRIMINANT rotates its functions.
  • UNIANOVA and GLM test for heteroskedasticity (Breusch-Pagan, F and White tests).

0.26.0 (2026-11-22)

UNIANOVA and GLM give robust standard errors, and optimal scaling groups variables into many categories more precisely.

  • UNIANOVA and GLM /ROBUST give robust estimates and tests (HC0 to HC4).
  • CATREG, CATPCA and related commands find the cut points of many normal-shaped groups precisely.
  • The Multidimensional Unfolding dialog starts from, or fixes, coordinates read from a file.

0.25.0 (2026-11-22)

More procedures read and write matrix data files, BOOTSTRAP gains two resampling methods built on residuals, and the DM command names work.

  • REGRESSION, ONEWAY, RELIABILITY and PARTIAL CORR read and write matrix data files.
  • BOOTSTRAP resamples residuals (RESIDUAL and WILD).
  • PREFSCAL fixes row or column coordinates and starts from given ones.
  • TSMODEL and TSAPPLY draw charts that compare the models, in syntax and in the dialogs.
  • DMLOGISTIC, DMROC, DMTREE and DMTABLES run LOGISTIC REGRESSION, ROC, TREE and CTABLES.

0.24.0 (2026-11-21)

GENLIN, NOMREG, GLM and UNIANOVA show more of how their tests are built, and GLM tests an effect against an error term you choose.

  • GENLIN prints estimable functions, L matrices, the iteration history and Lagrange multiplier tests.
  • NOMREG /TEST tests linear combinations of the parameters.
  • GLM and UNIANOVA print estimable functions and L matrices, and /TEST tests an effect against a chosen error term.
  • The Univariate, Multivariate and Generalized Linear Models dialogs offer these tables.

0.23.0 (2026-11-21)

REGRESSION can fit a subset of cases and report on the rest, NOMREG gives more tables, and GLM post hoc tests take a chosen error term.

  • REGRESSION /SELECT fits the selected cases and reports predictions and residuals for all; the dialog has a selection variable.
  • NOMREG adds cell probabilities, measures of association and the iteration history, also in the dialog.
  • GLM and UNIANOVA /POSTHOC take an error term with VS.

0.22.0 (2026-11-21)

REGRESSION tests sets of predictors, CROSSTABS writes its cells to a file, and GET and SAVE list how variables map.

  • REGRESSION /METHOD=TEST tests each set of predictors by its change in R square.
  • CROSSTABS /WRITE writes one record per cell to the file named by the new PROCEDURE OUTPUT command.
  • GET and SAVE /MAP list the variables with their names on both sides.
  • GLM and UNIANOVA read a SPECIAL contrast matrix column by column, the first column being the constant.

0.21.0 (2026-11-21)

ONEWAY gains trend tests, more Levene tests and effects rows, RELIABILITY gives McDonald’s omega, and LOGISTIC REGRESSION can fit a subset of cases. The dialogs have the new choices.

  • ONEWAY splits the between-groups sum of squares into trends (/POLYNOMIAL) and adds fixed and random effects rows.
  • ONEWAY /STATISTICS=HOMOGENEITY gives four Levene tests; scripts that read that table by column position should note its new second column.
  • RELIABILITY /MODEL=OMEGA gives McDonald’s omega.
  • LOGISTIC REGRESSION /SELECT fits the selected cases and reports the others.
  • DESCRIPTIVES /SORT orders the variables by any statistic.

0.20.6 (2026-11-20)

The window’s Excel export now puts all tables on one sheet by default, Windows shows Statscraft’s own icons for its data, syntax and output files, and the status bar shows the version.

0.20.5 (2026-11-20)

Fixes for exact tests, updates on Windows and sessions.

  • CROSSTABS exact tests use memory in proportion to what the computer has free, so larger tables get exact results.
  • Windows: Update in the window now installs reliably; a window of 0.20.4 or older needs the installer run once by hand.
  • A file session recovers its output after an interrupted save.
  • GET DATA /TYPE=TXT accepts /MAP after /VARIABLES.

0.20.4 (2026-11-20)

Plugin settings travel between computers, and OUTPUT MODIFY can hide a heading alone.

  • Edit > Plugin Settings can export and import templates; --plugin-template and the MCP server apply one for a run.
  • OUTPUT MODIFY VISIBLE=NO on HEADINGS hides only the heading and keeps its tables; use OUTLINEHEADERS to hide both.

0.20.3 (2026-11-20)

Command line and MCP sessions keep their output between runs, so several runs can be exported once at the end, and plugins can be checked for updates from the command line.

0.20.2 (2026-11-19)

The command line and MCP server reach further into the open window: undo the last change, read its output, close a syntax window, and apply plugins to its workbook.

0.20.1 (2026-11-19)

The command line and MCP server export the open window’s output to Excel, a web page or PDF, write charts as pictures, and can leave table titles out of the workbook.

0.20.0 (2026-11-19)

One Export dialog for the output, and plugins for agents.

  • File > Export… writes Excel, a web page or PDF, all items or only the selected tables.
  • The MCP server applies plugins to an agent’s workbook and lists a plugin’s settings.
  • A plugin’s own settings decide whether it writes comments, in the window and in Excel.
  • On Linux, Update installs the new .deb package itself.

0.19.1 (2026-11-18)

On Windows, running a plugin no longer flashes a console window.

0.19.0 (2026-11-18)

Plugins can update themselves: the window checks once a day and offers an Update button. See plugins.

0.18.0 (2026-11-18)

A large release: generalized linear mixed models, classic MANOVA, neural networks, simulation, time series models, survey sampling and many more commands, with dialogs for nearly all of them.

0.17.0 (2026-11-17)

CROSSTABS gets its full set of statistics, and TWOSTEP CLUSTER, DETECTANOMALY and CSORDINAL are new. Plugins gain design templates.

  • CROSSTABS gives every statistic (kappa, risk, McNemar, Cochran-Mantel-Haenszel and the rest), a case processing summary, and runs fast on large tables; the dialog offers them all.
  • TWOSTEP CLUSTER clusters cases from mixed variables, and DETECTANOMALY finds unusual cases.
  • CSORDINAL fits ordinal regression on a complex sample.
  • AGGREGATE has the percentage, fraction and count functions; DATA LIST reads date and time fields; SAVE writes the compression asked for.
  • Plugins: save settings as named design templates, one look per client.

0.16.0 (2026-11-16)

Plugins arrive: a program of your own can colour, comment and lay out custom tables, in the window and in Excel. SPECTRA, AREG and 2SLS are new.

  • Plugins colour cells, add comments and set fonts, borders and column widths. See plugins.
  • statscraft run --xlsx FILE --plugin PROGRAM applies a plugin to the workbook.
  • Every part of the output can be shown or hidden in the navigator. See the window.
  • SPECTRA, AREG and 2SLS for spectral analysis and regression with autocorrelated errors or instruments.
  • On Linux the window follows the GNOME light or dark setting.

0.15.0 (2026-11-16)

Time series, Bayesian statistics, power analysis, newer nonparametric tests and categorical principal components, each with its dialogs.

0.14.0 (2026-11-15)

Stata files, multiple imputation, loglinear models and a set of new procedures, each with its dialog.

0.13.0 (2026-11-15)

Survival analysis, distances and multidimensional scaling, and missing value analysis, each with its dialog.

  • KM, SURVIVAL and COXREG, with TIME PROGRAM for time-dependent covariates.
  • PROXIMITIES, PROXSCAL and ALSCAL.
  • MVA describes missing values and estimates the data under them.
  • LOGISTIC REGRESSION handles constant covariates and stepwise removal better.
  • With SPLIT FILE, saved variables keep the values of every group.

0.12.0 (2026-11-14)

GLM fits multivariate models, complex samples get regression, and MIXED and GENLIN grow.

  • GLM with several dependent variables: multivariate tests, SSCP matrices and custom tests, also in the Multivariate dialog.
  • CSGLM and CSLOGISTIC fit linear and logistic models on a complex sample.
  • MIXED gains eleven covariance structures, Kenward-Roger degrees of freedom and predicted random effects.
  • GENLIN /REPEATED fits generalized estimating equations.
  • Runs sent to the open window read relative file names from the caller’s folder.

0.11.0 (2026-11-13)

Generalized linear models, correspondence analysis, complex sample descriptives and a Graphs menu in the window.

  • GENLIN fits generalized linear models for many distributions and links.
  • CORRESPONDENCE analyzes two-way tables.
  • CSPLAN, CSDESCRIPTIVES and CSTABULATE estimate from complex samples.
  • NOMREG steps through effects, PLUM tests custom hypotheses, MIXED gives estimated marginal means and custom tests.
  • The window has a Graphs menu and new dialogs for regression, mixed models and complex samples. See the window.

0.10.0 (2026-11-13)

The GRAPH command arrives, along with PDF export, ordinal and multinomial regression and mixed models.

0.9.0 (2026-11-12)

Charts are drawn and can be edited in office programs, output can be saved, and every step an agent takes leaves syntax.

  • The output window draws charts, and saves them as PNG or SVG. See the window.
  • Charts open as editable charts in Excel, Word and PowerPoint, and OUTPUT EXPORT writes Word and PowerPoint files.
  • Output saves as a .scout file and opens again (OUTPUT SAVE, OUTPUT OPEN).
  • Each agent run is added to an Agent syntax window, and the MCP server can read and edit syntax windows. See the MCP server.
  • AI apps are connected in Edit > Settings > AI agents, including agents inside WSL. See Connect your AI agent.

0.8.1 (2026-11-12)

Help > Connect an AI agent connects Statscraft to AI apps with clicks, and the Data View stays evenly spaced in very large files.

0.8.0 (2026-11-12)

AI agents can now work with Statscraft through an MCP server.

  • statscraft mcp runs the MCP server. See the MCP server.
  • statscraft connect adds it to the AI apps on your computer. See Connect your AI agent.
  • Each release has a one-click bundle for Claude Desktop, a Claude Code plugin and the statscraft-analysis skill.
  • Each dataset has its own data window and each output document its own output window.
  • REGRESSION, FACTOR, MEANS, RECODE, COUNT and DESCRIPTIVES are faster on large data.

0.7.0 (2026-11-12)

Tables show variable and value labels, names or both, as SET TVARS and TNUMBERS choose, and every dialog ends with the same OK, Paste and Cancel buttons.

0.6.0 (2026-11-12)

The MATRIX language arrives, transformations know 185 functions, and SET BLANKS, EPOCH, FUZZBITS and SCALEMIN take effect.

0.5.0 (2026-11-12)

New procedures, input programs and output commands, with a portable Windows build and a macOS app.

  • FACTOR, QUICK CLUSTER, CLUSTER, DISCRIMINANT, LOGISTIC REGRESSION, UNIANOVA, GLM and ANOVA.
  • INPUT PROGRAM, FILE TYPE, REPEATING DATA and the other input program commands.
  • MATRIX DATA, REPORT and the OUTPUT commands, which export to Excel, HTML, text and CSV.
  • Dialogs for these procedures in the window.
  • A portable Windows ZIP and a macOS app, both updating from the window.

0.4.0 (2026-11-11)

The window asks before closing unsaved work, has one Settings dialog, and gains grid selection and more dialogs.

  • Nothing unsaved closes without asking.
  • Edit > Settings holds the editor, grid, output and update settings.
  • Cells, headers and row numbers can be selected with the mouse, and Delete clears them.
  • Dialogs for Linear Regression, Reliability Analysis, the nonparametric tests and Partial Correlations.
  • New commands: TITLE, SUBTITLE, PRINT, WRITE, XSAVE and more.

0.3.0 (2026-11-11)

More procedures, restructuring and merging, and Excel files in and out.

  • REGRESSION, RELIABILITY, NPAR TESTS, PARTIAL CORR, MULT RESPONSE and TREE.
  • VARSTOCASES, CASESTOVARS, FLIP, UPDATE, ADD FILES and MATCH FILES.
  • GET DATA reads Excel workbooks; SAVE TRANSLATE writes CSV, tab-delimited text and Excel.
  • Dates, times and currencies show in their formats in tables, the Data tab and Excel.
  • Command line sessions keep settings, the working folder and random numbers between runs.

0.2.0 (2026-11-11)

The Statscraft name and look everywhere, right-click menus in the grids, and more CTABLES formats.

  • A new app icon, colours and bundled fonts.
  • Right-click menus in the Data and Variables tabs.
  • INCLUDE and INSERT read the file at once, so a macro library’s macros can be called right after it.
  • CTABLES has more summary formats and dates in titles.

0.1.1 (2026-11-10)

FREQUENCIES and RANK are complete, database connections are encrypted and faster, and the window gains the Variables tab.

  • FREQUENCIES and RANK run with every subcommand.
  • Database connections use TLS and store and read large datasets much faster.
  • The Variables tab with its editors, and Rank, Automatic Recode and Split File dialogs.
  • Syntax editor themes.
  • Macros last across the runs of a session.

0.1.0 (2026-11-10, early release)

The first version for people who want to try Statscraft and tell us what breaks. Please report problems on the Issues page of the GitHub repository.

  • Reads and writes .sav and .zsav files, with labels, missing values, multiple response sets and dates.
  • Runs the statistics command syntax: macros, transformations, and procedures from FREQUENCIES to CTABLES.
  • Custom tables with nesting, totals, multiple response sets and significance tests.
  • A desktop window with data, syntax and output views, and a command line built for scripts and AI agents.
  • Stores datasets in SQLite, PostgreSQL, MySQL, MariaDB or Dolt.