Actions

式マネージャー

From LimeSurvey Manual

Revision as of 12:19, 13 July 2018 by Bravehorse (talk | contribs) (Created page with "{| class="wikitable" !質問コード!!関連!!質問 |- |Q1||1||名前は何ですか。 |- |Q2||Q1||{Q1}さん、何歳ですか。 |- |Q3||Q2||{Q2}歳なのですね。結...")
注意: この機能はLimeSurvey 1.92以降で利用できます。

クイックスタート

概要

アンケートをカスタマイズするには、通常次のことを決めます。

  1. ナビゲーション/分岐 - 質問の順番を変更します。
  2. テーラーリング/パイピング - 質問の文言調整(先行する回答の引用、数や性別による文の結合など)、カスタムレポートの生成(評価点数、アドバイスの提示など)
  3. 検証 - 回答が条件(最大値、最小値、入力パターンなど)を満たすようにします。

式マネージャー(EM)では、各機能のロジックを指定する直感的な方法が提供されています。関数を呼び出しているものであっても、標準的な数式として書くことができるものは、ほとんどが有効な式になります。 EMは現在、70の関数が利用でき、より多くの機能をサポートするよう、簡単に拡張することができます。また、(SGQA名ではなく)人間が読める変数名を使用して変数にアクセスすることもできます。

以下のセクションで、式マネージャーを使う主な場面を紹介します。

関連(ナビゲーション制御/分岐)

アンケートによっては、"Gotoロジック"を使用して、質問1でCと答えた場合は質問5にジャンプしたりします。このアプローチは、検証が難しく、質問を並べ替えるときにロジックが壊れてしまうため、大きな制約があります。EMでは、質問が有効かどうかを決めるすべての条件を、ブール値の関係式を使用して指定します。質問が関連ありとなる場合は質問が表示され、それ以外の場合は「適用外」となり、データベースにはNULL値が格納されます。これは条件エディターで実行できるものと似ていますが、EMではより複雑で強力な条件を簡単に指定でき、さらにSGQA名ではなく変数名を使用できます。

この画像では、アンケートの関連性ロジックを確認する例を示しており、ここでは、体格指数(BMI)を計算します。関連式は、変数名の直後の角カッコで示されています(緑色)。体重、体重の単位、身長、身長の単位の関連式はすべて1です。つまり、これらの項目は常に質問されます。しかし、BMIの関連式は、 {!is_empty(height) and !is_empty(weight)}となっており、BMIは、身長と体重の両方を入力しないと計算しないようになっています(ゼロで割るリスクも避けています)。また、「Report」の質問は、主たる4つの質問(身長、身長の単位、体重、体重の単位)すべてに回答した場合にのみ表示されます。

関連は以下の場所て表示・編集ができます。

質問レベルの関連の閲覧/編集

この式は、体格指数(BMI)を計算します。最初に身長と体重を入力した場合のみ対象となります。

こちらがBMI質問の編集画面です。

関連式を入力するときは中括弧を使用しないようにしてください。

グループレベルの関連の閲覧/編集

これは、国勢調査の調査例です。最初のページで、回答者に同居人数を尋ね、結果が"cohabs"変数に格納されています。このページは、複数の同居人がいる場合(つまり、このページは同居している2番目の人物に関するもの)で、回答者と「人物1」の関係(p1_rel)を指定した場合にのみ表示されます。

ご覧のように、グループには質問レベルの関連基準もあり、こうした質問は、先行する質問に回答したときにのみ表示されます(例:{!is_empty(p1_sex)})。EMは、グループと質問レベルの関連を結合します。グループ内の質問は、グループ全体が関連する場合にのみ尋ねられます。次に、関連するグループ内の質問のサブセットのみが尋ねられます。

その質問のグループレベルの関連を編集する画面は次のとおりです。

関連式を入力するときは中括弧を使用しないようにしてください。

カスタマイズ/パイプ

EMを使用すると、単純な、または複雑な条件付きの質問を簡単に作成できます。例えば、"[製品]を購入したと回答しました。よかった点は何ですか?"のように、単純な「置き換え」が必要な場合があります。また、"[Mr./Mrs.] [LastName]、アンケートを完了してもよろしいですか?"のように、条件付きの置き換えが必要な場合もあります。この場合、回答者の性別に基づいてMr.かMrs.を使用します。また、例えば、数学的計算に基づいてさらに複雑な置き換えが必要になることもあります。EMは、このような場合のカスタマイズ/パイプをサポートしています。

条件式

体格指数の例では、身長と体重の入力単位がメートル法であってもメートル法でなくても、BMIが計算できることを示しています。

ここで、weight_kgは、{if(weight_units == 'kg', weight, weight * .453592)}となっています。このif()関数では、キログラムで体重が入力されていた場合は入力値をそのまま採用し、それ以外の場合は入力値(単位はポンド)に0.453592をかけてキログラムに変換します。同様に、変数height_mは、身長がインチ単位で入力されていてもメートル単位の身長を計算するようになっています。

BMIは、{weight_kg / (height_m * height_m)}という式で計算されます。

最後に、回答者に対し、条件付きでカスタマイズして入力した内容を表示します。("身長2メートル、体重70キロと回答しました。")

上の画像ではわかりにくくなっていますが、weight_statusは入れ子のif()ステートメントを使用し、その人物がやせているのか肥満なのかを分類します。その式をロジックビューで見ることができます。

この質問の編集ウィンドウから、次の2つのことがわかります。

  1. 中括弧で表現を囲む必要があります
  2. 式は、例えばこの例のように、ネストされた条件付きロジックを読みやすくするため、複数の行にまたがって記述することができます。

カスタマイズされた質問・解答・レポート

注意: 同じ質問ページの選択ボックスで回答オプションを利用できるようにすると、動的カスタマイズが機能しないことがあります。これは、選択オプション内で使えない<span>タグを挿入してしまうことに起因しています。

この例は、BMIレポートを示しています。

同じ質問の編集ウィンドウです。

ご覧のように、中括弧で囲われた部分は式として扱われるので、前の画像では構文ハイライト(色分け)されています。タイプミスや定義されていない変数名や関数のような誤字があった場合、EMはこのようなエラーを表示します。例えば、height_unitは未定義の変数名(実際はheight_units)、rnd()は未定義関数(正しくはround())です。いずれの場合も、エラーを赤い枠で囲み、見つけて修正しやすくなっています。

また、入力された値の一覧やカスタマイズされたアドバイスなど、複雑なレポートをすばやく作成できます。

質問のどの部分がフリーテキストで、どの部分が式マネージャーで解析する必要があるかをLimeSurveyが判断するため、すべての式をCurly Bracesで囲む必要があります。

検証

EMは、高度な質問オプションがどのように機能するかを制御します。回答の数、個々の入力値や合計の最小値/最大値を制限したり、入力された値が指定された文字列パターンと一致していることを確認したりします。いつものように高度な質問オプションの入力を行いますが、これらのフィールドの値はどれも式と見なされるため、他の質問と複雑な条件で組み合わせ、最小値/最大値基準を設定することができます。

これらのすべてのケースでは、高度な質問オプションは常に式と見なされるため、中括弧を使用することはありません。

|サンプルアンケートページには、検証のために式を使用した実例がたくさんあります。

はじめに

LimeSurveyでは、新しいExpression Manager(EM)モジュールを使用して、より複雑な分岐、評価、検証、およびカスタマイズがサポートされています。LimeSurveyがサーバー内で行う置換、条件、評価の管理方法を置き換えることができます。また、ランタイムデータベースの読み込みのほとんどが不要になるため、処理速度が大幅に向上します。EMはDr. Thomas White(TMSWhite)が開発しました。

このwikiページは、Expression Managerの構文と機能のリファレンスです。

主な定義

  1. :  中括弧で囲まれたもの
    • 開く中括弧の直後または閉じる中括弧の直前に空白がない
    • 式の内容はEMが評価するため、数式、関数、複雑な文字列と日付処理を含めることができます。
  2. カスタマイズ: "パイピング"とも呼ばれますが、これは条件付きでテキストを変更するプロセスです。
    • すべての'置換フィールド'、参加者データ、回答データにアクセスできます。
    • 質問、回答、およびそのプロパティにも簡単にアクセスできます。
  3. 関連式:  質問を表示するかを制御する新しい質問属性
    • 関連式がある場合、その関連性が真と評価された場合にのみ質問が表示されます。
    • 内部では、すべてのarray_filterコマンドとarray_filter_excludeコマンドがサブ質問レベルの関連になります。
  4. 質問タイプ:  データベースに計算やレポートを保存する新しい質問タイプ
    • これはテキストを表示する質問のようなものですが、"この質問をいつも隠す"を設定しても、その内容はデータベースに保存されます。
  5. 質問コード:  EMで使われる変数
    • これは質問の目的を示すわかりやすい名前にすることができ、複雑なロジックを読みやすくなります。
    • 有効な質問コードは数字で始めることはできないので、質問番号を質問コードにするときは、単に"q1"、"q1a"、"g1q2"のようにしてください。
    • 現在のところ、データをSPSSまたはRにエクスポートすると、これが変数名になります。したがって、統計分析を行う場合は、ユニークにしなければなりません。

EMを使わなければならないのか?

短い答えは「いいえ」ですが、「はい」でもあります。

EMは、既存のアンケートと完全に後方互換性があります。LimeSurveyバージョン1.91+以前で使用されていたスタイルの条件と評価は、引き続き使うことができます。

ただし、EMでは、LimeSurveyが内部的にどのように条件を処理するかについて完全に置き換えられています。条件エディタを使用して条件を作成したり管理したりすることはできますが、LimeSurvey 1.92ではそれらは同等の関連式に変換されます。アップグレードの一環として、LimeSurvey 1.92では既存のすべての条件が関連式に自動変換されます。

これにより、新旧のいいとこ取りができます。これまで通りLimeSurveyを使い続けることもできますが、同等の関連式が表示されるので、関連式に徐々に移行することもできます。

条件と関連の両方を使えるか?

はい。一部の質問で条件エディターを使用し、他の質問で関連エディターを使用することができます。質問を保存すると、条件は自動的に関連に変換されます。

条件エディターを使用している場合、手動で入力した関連式は上書きされます。したがって、すでに条件があって、関連を手動で編集したい場合は、まずその質問の条件を削除してください。具体的には、生成された関連式をテキストエディターにコピーし、条件メニューからその質問の条件をすべて削除し(関連も削除)、質問を編集し、テキストエディタからその質問の関連フィールドに貼り付け、質問を保存します。生成された関連式を削除せずに条件を削除したいというニーズが場合、一括変換プロセスの追加開発を検討します。

条件と関連のどちらを選ぶべきか?

各々の長所と短所のリストを以下に示します。

スタイル 長所 短所
条件 1. シンプルな条件を作成するための優れたGUI
2. サポートチームにより文書化され理解しやすいGUI
1. 簡単な比較のみをサポートし、AND/OR条件はうまく機能しない
2. カスケード条件が不安定
3. データベースアクセスが遅く、アンケートに時間がかかる
4. 条件のリロードで不具合がレポートされている
5. GUIに拡張性がなく、何十、何百、または何千もの質問があるときにうまくいかない。
6. SGQA名を使用しなければならないので、紙ベースのアンケートを変換するのが遅いかもしれない
7. 複雑な分岐が必要な場合、カスタムコードロジックを書くプログラマーが必要なことがある
関連 1. 80以上の関数と数学/文字列演算子を含む非常に複雑なロジックのサポート
2. カスケードロジックの完全サポート
3. 高速 - 余計なデータベースアクセスがなく、1000以上の質問があるアンケートをサポート
4. SGQAコードを必要としないため、リロードロジックで問題が生じない
5. 構文ハイライト機能は1000以上の質問があるアンケートにも対応
6. 既存の紙ベースのアンケートを電子化に簡単かつ迅速に対応
7. プログラマーを必要とせずに半構造化インタビューや疫学調査を容易にサポート
1. 単純な条件のためのGUIがない(代わりに構文ハイライト機能を使用)
2. まだ新しい機能で、サポートチームがまだEMをマスターしていない

LimeSurvey 1.91+の仕組みに満足していれば、変える理由はありません。

EMのメリットは他にあるか?

EMを使うべき理由がいくつかあります。

  1. 計算 - 任意の計算式を作成することができます。
    • 一般的な数学的演算子と関数のすべてを利用できます。
    • 70以上の数学、日付、および文字列処理関数を利用できます。
    • 必要な場合、新しい関数を簡単に追加できます。
  2. データベースへの計算の保存
    • シンプル/複雑な式や評価点を計算し、JavaScriptを要せずにデータベースに保存できるようになりました。
    • 式の質問タイプを使用してます。
  3. 評価
    • 以前は一部のみサポートされていましたが、すべての質問タイプからの評価やスケールの作成が可能になりました。#*カスタマイズを使用すると、同じページであっても、必要な場所で、途中または合計の評価点数を表示できます。
    • 評価点数に基づいて生成されたレポートをより細かくコントロールできます。
    • JavaScriptを使用せずに評価点数をデータベースに保存することができます。
    • 評価点数は、JavaScriptやCSSを使わずに非表示にできます。
  4. 代替フィールド
    • {INSERTANS:SGQA}を使う代わりに、質問コードを使用すると、読みやすく、検証しやすくできます。
    • これにより、すべてを動作させるため質問を編集してSGQAコードを変更する必要もなくなります。
  5. カスタマイズ - 他の値に基づいてテキストをカスタマイズして表示できます。#*適切な敬称を使用する(例: "Hello [Mr./Mrs.] Smith")。
    • 単数/複数に基づき文法的に正しい文章を出力する(例: "You have 1 child"と"You have 2 children")
    • 性や数に基づいて動詞や名詞を変化させる
  6. 新しい変数の属性 - 次の項目にアクセスして調整できます。
    • (接尾辞なし) - qcode.codeの別名
    • .code - 質問が表示された場合は選択された回答コード(それ以外の場合は空白)、またはテキスト値(コード化されていない質問の場合)
    • .NAOK - .codeと同じですが、非表示となる場合であっても計算やリストに含めることができます。
    • .value - 質問が表示対象となる場合はその質問の評価値(それ以外の場合は空白)、またはテキスト値(コード化されていない質問の場合)
    • .valueNAOK - .valueと同じですが、非表示となる場合であっても計算やリストに含めることができます。
    • .shown - ユーザーに表示される回答(これは{INSERTANS:xxx}の機能です)
    • .qid - 質問ID
    • .gid - グループID
    • .sgqa - 質問のSGQA値
    • .jsName - (このページで定義されているかどうかに関係なく)質問に対する正しいjavascript変数名
    • .qseq - 質問の順番(0から開始)
    • .gseq - グループの順番(0から開始)
    • .mandatory - 質問が必須かどうか(Y/N)
    • .question - 質問のテキスト
    • .relevance - 質問の関連式
    • .grelevance - グループの関連式
    • .relevanceStatus - 質問が表示条件を満たしているかどうか(1/0)
    • .type - 質問タイプ(1文字のコード)
  7. ページ内の動的変更
    • すべての関連、計算、およびカスタマイズはページ内で動的に機能するため、値の変更によりページが即座に更新されます。
    • したがって、関連の評価結果に基づいて、質問が動的に表示/非表示になります。
    • また、ページ内の回答に基づいて質問も動的に調整されるため、合計値、カスタマイズされた文、カスタマイズされたレポートをみることができます。
  8. 新しいデータ入力画面
    • 現在のデータ入力システムを使用するだけでなく、単ページアンケートでも使用することもできます。
    • ページ内の関連とカスタマイズがサポートされており、データ入力担当者はタブキーで入力を進め、関連する回答を入力するだけで済みます。
    • この特徴は、データ入力者がカスタマイズによる動的変化を確認する必要がある場合に重要です。
  9. ほとんどのカスタムJavaScriptの必要性を排除
    • EMは、複雑な計算、点数づけ、カスタマイズ、および条件付きロジックを容易にサポートします。
    • JavaScript(カスタムレイアウトや条件付きの質問サブ要素など)を必要とするものもありますが、JavaScriptによって、EM関数を使用してSGQAの代わりにQcodeで質問にアクセスし、上記の質問属性にアクセスすることができます。

式マネージャーのその他の新機能

条件エディターを引き続き使用するか、または関連式を手動で作成するかにかかわらず、次のような利点があります。

  1. より複雑な検証基準を作成することができます。
    • すべての高度な質問属性(max_answers、min_num_value_n、max_num_valueなど)は式を使用できます。したがって、最小値・最大値の条件は、同じページの先行する質問の回答に基づいて簡単に調整できます。
    • EMは正規表現ベースの検証をすべて処理するので、pregと式ベースの質問属性を強固に組み合わせることができます。
  2. 質問とグループの並べ替え(または削除)が容易にできます。
    • バージョン1.92より前のバージョンでは、並べ替えによって条件が成立しなくなる可能性があると認識された場合、質問やグループの並べ替えはできませんでした。同様に、ある質問に依存する質問がある場合は、その質問を削除できませんでした。
    • EMの構文強調表示により、これから宣言して使おうとしている質問を確認し、検証することが簡単にできです。したがって、いつでも質問やグループを並べ替えたり、削除したりすることができます。EMは潜在的なエラーを表示するためにすべての構文強調表示を更新します。
    • このようなレビューに役立つように、質問並べ替えの表示が強化されました。質問の関連式とカスタマイズが表示されるので、変数がピンク(宣言する前に使用されていることを意味します)になったかどうかをすぐに確認できます。
  3. 質問やグループのナビゲーション番号は常に利用可能で正確です。
    • バージョン1.92以前は、複雑な条件があった場合、ナビゲーション番号は利用できませんでした。
    • EMでは、正確であることを保証されています。
    • 前の質問に戻り、答えを変えてから、後ろにジャンプする(または送信する)こともできます。
      • 前進すると、EMは関係するすべての質問/グループを再検証します。
      • 表示条件に該当しなくなる質問があれば、データは内部で一貫性を保つためデータベースにNULLが格納されます。
      • 質問が表示条件に該当したり、新たに必須条件または検証ルールに適合しなくなった場合、EMはそのページで停止し、ユーザーが最終ページに飛ぶ前にそれらの質問に答えなければならないようにします。
  4. 条件から関連への自動変換
    • データベースをアップグレードすると、条件を持つ既存のすべてのアンケートに関連式が生成されます。
    • アンケートをインポートするたびに、関連式が必要に応じて作成されます。
    • 条件を追加、削除、または変更すると、EMは適切な関連式を生成します。
  5. 便利な構文強調表示
    • SGQAコードを入力した場合であっても、EMが関連式を表示するときは、Qcodeが表示されます。読みやすくするためです。
    • すべての変数は、現在の質問の前後(または現在のグループの前後)に宣言されたかどうかを示すために色分けされています。これにより、変数を宣言する前に、関連(array_filterを含む)、カスタマイズ、検証式で使用する変数を使うケースをすばやく検出して修正できます。
    • 色付けされた変数の上にマウスを移動すると、その質問に関する追加情報が表示されます。これには、グループ番号、質問番号、Qcode、質問のテキスト、利用可能な回答の選択肢(該当する質問タイプの場合)が含まれます。
      • 回答の選択肢のリストは、次のような構文を使用します: 'answers':{key:val, ... }.
      • keyは'scale~code'という構文となります。scaleは回答の尺度(二元スケールなど)、codeは回答コードです。
      • valは'value~shown'という構文となります。valueは評価値(評価を使う場合。その他の場合はコード)、shownは表示される値です(Qcode.shownなど)。
      • つまり、多くの場合、アンケートで評価モードを使わずに計算を使用できます。ユニークで、10進数でなく、負の数でない回答オプションを列挙する場合は、Qcode.code値の計算を行うことができます。
  6. アンケートロジックとコンテンツ全体の簡単なレビュー
    • 新しいアンケートロジック表示機能があり、アンケート(またはグループ、質問)に関するすべての情報を1ページに表示できます。
    • 選択したスコープ(アンケート、グループ、質問)のグループ、質問、サブ質問、回答レベルの詳細を表示します。
    • また、関連、サブ質問レベルの関連(array_filterとarray_filter_exclude)、生成された検証式(pregと合計の最小値・最大値、値の数などの検証ルール)、およびすべての空白以外の質問属性も表示されます。
    • すべて構文強調表示されているため、潜在的な構文エラー(括弧の不一致、未宣言の変数使用など)を発見できます。
    • 構文強調表示により、アンケートのナビゲーションと編集が迅速にできるようになります。
      • 変数名をクリックすると、その質問を示すブラウザウィンドウ(またはタブ)が開き、編集することができます。
      • グループ名をクリックすると、グループの並べ替えビューを表示するブラウザウィンドウ(またはタブ)が開き、簡単に質問を移動できます。
      • すべての質問属性も構文強調表示されています。これにより、高度な質問オプション内で式を設定したり表示したりすることができます(式の最大値/最小値/合計など)
    • EMの製作者は、似たようなビューを使い、疫学者と治験審査委員会が高度に分岐する、何千もの質問があるアンケートを検証し、認可できるよう協力しました。

始めてみる

式マネージャーを始める最善の方法は以下のとおりです。

式マネージャーでは、どの機能が拡張/置換されたのか?(LimeSurvey 1.91)What Functionality does Expression Manager Extend/Replace? (LimeSurvey 1.91+から)

条件 → 関連

どの質問が表示されるかを制御する条件。一般的な構文は、111X2X3 == "Y"'のようなSGQA 演算子 値でした。条件はANDまたはORを組み合わせることができますが、ANDとORを混在させることは困難でした。条件自体は独立したテーブルに保存され、LimeSurveyのコードの大部分は条件の管理に費やされていました。膨大なデータベースアクセスのため、多数の条件を処理すると、パフォーマンス上の深刻な問題が発生する可能性がありました。さらに、条件が質問やグループに一旦割り当てられると、それらを並べ替えたり削除したりすることはできませんでした。

評価 → 式と細かいカスタマイズ

評価機能により、一連の質問から評価値を算出することができます。ただし、表示中のページ内で動的に変更することはできず、またその値はデータベースに保存されませんでした。

置換 → 細かいカスタマイズ

ユーザーは、先行する回答に基づいてメッセージや質問をカスタマイズできます。たとえば、{TOKEN:FIRSTNAME}さん、あなたは{INSERTANS:111X3X4}が好きなスポーツだと回答しましたのような質問が可能です。しかし、条件付きのカスタマイズ(性別に応じて"Mr."や"Mrs."をつけるなど)や、動詞や名詞を変化させたりすることはJavaScriptなしにはできませんでした。質問をカスタマイズするようなアンケートを実装することはできましたが、すべての組み合わせに対する個別の質問が必要であり、表示する質問を決定する複雑な条件が必要でした。

検証

Question could be validated with Regular expressions, or minimum/maximum values, or let an SGQA response serve as the minimum or maximum value.  However, validations could not be based upon calculations of other variables without fancy JavaScript.

Equations were not supported without fancy JavaScript.

式の質問タイプ

JavaScriptを使用せずに式をデータベースに保存すること(評価の最終スコアなど)はできませんでした。

式マネージャーはどのように機能を拡張するのか?

式マネージャーは、カスタムJavaScriptを必要とする複雑な機能をより簡単に実現できるLimeSurveyの新しいコアモジュールです。LimeSurveyが条件と評価を管理する現場の方法に取って代わるものです。

式マネージャー(EM)向けの新しい用語

EMは次のように機能を定義しています。

  • 関連に基づく分岐 - 質問が関連する場合は表示し、そうでない場合は非表示にします(データベースにNULLとしてマークします)。すべての質問タイプと各々のグループに対して新たな関連フィールドが追加されています(したがって、各質問に同じ条件をコピーしたりすることなくグループ全体に条件を設定でき、また、グループレベルと質問レベルの条件を組み合わせることができます)。
  • カスタマイズ - どの質問を聞くべきかを決めたら、カスタマイズ(パイピングとも呼ばれる)によって、質問方法を指定します。これは簡単な置き換え(例:{TOKEN:FIRSTNAME})だけでなく、性別や人数によって動詞や名詞の変化も可能です。また、他の質問に回答したか(または回答内容)に基づいて、送信するメッセージを変更することもできます。
  • - EMでは、式の結果を格納する新しい質問タイプ(式)が追加されました。式の結果は、たとえページ上で非表示であって、計算結果はデータベースに書き込まれます。これにより、裏で行われるスコア計算、複雑な式に基づくナビゲーション、評価、およびレポートの作成が可能になり、データベース上で簡単に利用することができます。

関連とカスケードされた関連

すべての質問タイプで、質問が表示されるかどうかを制御する関連オプションが追加されました。EMは、アンケートに登場する順に関連式を処理します。式が真(または式がない - 古い形式のアンケート向け)の場合、質問が表示されます。関連が偽の場合、質問は非表示になり、その値はデータベースでNULLになります。グループに関連する質問がない場合、グループ全体がスキップされます。

さらに、式に含まれる変数のいずれかの関連が偽の場合、式は常に偽と評価されます。これにより関連の入れ子が可能になり、各々の質問に対して非常に長い関連式を書く必要がなくなります。

たとえば、5つの質問Q1〜Q5があり、Q1が答えられたらQ2、Q2に答えられたらQ3などを表示したいとします。関連式は次のようになります。

質問コード 関連 質問
Q1 1 名前は何ですか。
Q2 Q1 {Q1}さん、何歳ですか。
Q3 Q2 {Q2}歳なのですね。結婚していますか。
Q4 Q3 == "Y" {Q1}さん、結婚して何年になりますか。
Q5 Q4 {Q1}さん、子供は何人いますか。

The relevance calculations also work in JavaScript - so you could put all the above questions on one page and it would still work as expected.  In fact, EM totally replaces how EM processes Survey vs. Group vs. Question-at-a-time survey formats.  They now all use the exactly same navigation engine so they work identically regardless of survey style.

As long as you are on the same page, any data you entered will still be there, just hidden.  So, if you enter some information, then choose an option that makes them irrelevant, then make them relevant again, your answers will still be available.  However, as soon as you move to a different page, all irrelevant responses will be lost to integrity of the dataset.

グループレベルの関連

Expression Manager also supports group-level relevance.  This makes it easier to implement looping.   Say you want to collect information about up to 10 entities (such a products or people in a household), where you first determine how many entities need follow-up (such as by asking how many people live in a household, or having people check which products they like from a long list).  After knowning how many entities need follow-up, you can use Group-level relevance like {count >= 1}, {count >=2}, ... {count >= 10} for each of the 10 groups of follow-up questions.  Within each group, you can have question-level conditional logic (e.g. gender or age-specific follow-up questions for each subject).  The question and group-level relevance equations are ANDed together to determine which should be shown.

カスタマイズ/パイプ

Anything within curly braces is now treated as an Expression (with one exception described below).  Expressions have acccess to all of the LimeReplacementFields, all of the variables (via several aliases), all typical equation operators (mathematical, logical, and comparison), and dozens of functions (that even work dynamically on the client-side).

Using these equations, you can do things such as:

  1. Conditionally show tailored messages to the respondants based upon prior responses
  2. Create Assessments and show Assessment results (or conditionally branch or show messages) based upon those results, all without using the Assessments module itself
  3. Conjugate verbs and decline nouns within questions, answers, and reports.
  4. Show summaries of responses before the "Show your answers" page at the end of the survey

There is a new question type called  Equation.  It is like a Boilerplate questions, except that it stores the value of what is displayed in the database.  So, if the Equation Question text contains an Assessment computation, that value would be stored in the database in a variable that can be displayed within public or private statistics.

This solves a common request for storing Assessment scores within the database

構文

Anything contained within curly braces is now considered an Expression (with one exception:  there must be no leading or trailing whitespace - this is needed to ensure the Expression Manager does not try to process embedded JavaScript).

Note, it is OK for expressions to span multiple lines, as long as there is no whitespace after the opening  curly brace or before the closing curly brace.  This is especially helpful for nested if() statements like this:

{if(is_empty(PFTotals),
 '',
 if(PFTotals >= -5 && PFTotals <= -4,
   'Very Soft',
   if(PFTotals >= -3 && PFTotals <= -2,
     'Soft',
     if(PFTotals == -1,
       'Somewhat Soft',
       if(PFTotals == 0,
         'Moderate',
         if(PFTotals == 1,
           'Somewhat Hard',
           if(PFTotals >= 2 && PFTotals <= 3,
             'Hard',
             if(PFTotals >= 4 && PFTotals <= 5,
               'Very Hard',
               ''
             )
           )
         )
       )
     )
   )
 )
)}
Expression Manager supports the following syntax:
  • All standard mathematical operators (e.g. +,-,*,/,!)
  • All standard comparison operators (e.g. <,<=,==,!=,>,>=, plus these equivalents:  lt,le,eq,ne,gt,ge)
  • Parentheses (so you can group sub-expressions)
  • Conditional operators (e.g. &&,| | and these equivalents: and,or)
  • Single and double-quoted strings (which can each embed strings with the other quote type)
  • Comma operator (so can have a list of expressions and just return the final result)
  • Assignment operator (=)
  • Pre-defined variables (to refer to questions, question attributes, and responses) - e.g. all of the SGQA codes
  • Pre-defined functions (there are already 70+, and it is easy to add more)

演算子

EM syntax follows normal operator precedence:

Level Operator(s) Description
1 () parentheses for grouping or calling functions
2 ! - + unary operators: not, negation, unary-plus
3 * / times, divide
4 + - plus, minus
5 < <= > >= lt le gt ge relative comparisons
6 == != eq ne equality comparisons
7 and logical AND
8 or logical OR
9 = assignment operator
10 , comma operator

Note, for consistency between JavaScript and PHP, the plus operator (+) does addition if both operands are numeric, but does concatenation if both parts are non-numeric strings.  However, we recommend using the join() function for concatenation, as that makes your intent more clear, and avoids unexpected results if you were expecting strings but got numbers instead (or vice versa).

代入演算子(=)を使用する際の注意

Note, you should avoid using the assignment operators unless absolutely necessary, since they may cause unexpected side-effects.  For example, if you change the value of a previous response, the cascading relevance and validation logic between that question and the current question is not re-computed, so you could end up with internally inconsistent data (e.g. questions that stay answered but should have been NULLed, or questions that are skipped but should have been answered).  In general, if you want to assign a value to a variable, you should create an Equation question type, and use an expression to set its value.  However, there are some rare times that people really need this operator, so we made it available.

To help caution you about this operator, it is shown in red font within the syntax equations (so that you don't confuse it with "==")

Using Assignment Operator

The main reasons you may want to use assignment are:

  • You need to set the default value for a question that does not accept defaults via equation (such as list radio, where the user interface lets you pick one of the answer options, but does not let you enter an equation).  However, be careful, as LimeSurvey will not be able to validate that your equation generates one of the allowable answers for that question.
  • You need to forcibly change the response to a previous question based upon a later response
  • etc...

You can use all expression manager system for this purpose. It's better to use an Equation question type to this purpose.

Some example:

  • Set answer to a short text question in lowercase : {QCODE=strtolower(QCODE.NAOK)}
  • Set a default answer to an array question type at start of a survey : {Q1_SQ1=(is_empty(Q1_SQ1.NAOK),"A99",Q1_SQ1.NAOK)}
  • Set a default answer to an array texts question type at start of a survey : {Q1_SQY1_SQX1 = (is_empty(Q1_SQY1_SQX1.NAOK),"Inserted answer", Q1_SQY1_SQX1.NAOK)}
  • Set an answer with condition : {QCODE=if(YesNo="Y","A1","")}

XSS セキュリティ

With XSS enable, some expression manager system can not be used :

  • starting a HTML tag in expression but ending in another expression
  • use a complex expression in URL.

Example and workaround

  • {if( 1 ,"<strong>","")}information{if( 1 ,"</strong>","")} is broken with XSS security, here you can use {if(1,"<strong>information</strong>","information")}
  • <a href="/script.php?value={if(QCODE == "Y","yes","no")}">next</a>, here you can use an equation question because using a complete question code is OK : <a href="/script.php?value={EQUATION.NAOK}">next</a>

変数へのアクセス

Expression Manager provides read-only access to whichever variables we might need.  For backwards compatibility, it provides access to the following:

  • TOKEN:xxx - the value of a TOKEN (e.g. TOKEN:FIRSTNAME, TOKEN:ATTRIBUTE_5) (Only for NOT anonymous survey).
  • INSERTANS:SGQA - the display value of an answer (e.g. "Yes"). For Expression Manager it's the same that using {QCODE.shown}.
  • All {XXX} values used by templates.
  • In question text, you can use {QID} replaced by the question id and {SGQ} replaced by the SGQA of the question

In addition, Expression Manager lets you refer to variables by the Question Code (the 'title' column in the questions table within the database).  This is also the variable label used when you export your data to SPSS, R, or SAS.  For example, if you have questions about name, age, and gender, you could call those variables name, age, and gender instead of 12345X13X22, 12345X13X23, and  12345X13X24.  This makes equations easier for everyone to read and validate the logic, plus makes it possible to shuffle questions around without having to keep track of group or question numbers.

Important: It is only safe to refer to variables that occur in preceding pages or questions.

Furthermore, Expression Manager lets you access many properties of the Question:


Syntax Meaning Example Example Result
Qcode an alias for Qcode.code {implode(',',name,gender)} 'Tom','M'
Qcode.code the selected response code for the question if it is relevant (otherwise blank), or the text value if it is not a coded question {implode(',',name.code,gender.code)} 'Tom','M'
Qcode.NAOK same as Qcode - see discussion of NAOK {gender.NAOK} 'M'
Qcode.value the assessment value for the question if it is relevant (otherwise blank), or the text value if it is not a coded question {gender.value} '1'
Qcode.valueNAOK same as Qcode.value - see discussion about NAOK {gender.valueNAOK} '1'
Qcode.shown the dispay value for the question {implode(',',name.shown,gender.shown)} 'Tom','Male'
Qcode.question the text of the question {gender.question} 'What is your gender?'
Qcode.mandatory whether the question is mandatory (Y/N) {gender.mandatory} 'N'
Qcode.qid the internal question number (not the sequential number) {gender.qid} 337
Qcode.type the question type {gender.type} 'G'
Qcode.jsName the correct javascript name for the question, regardless whether declared on or off this page {gender.jsName} 'java1827X3X337'
Qcode.gid the internal group number (not the sequential number) {gender.gid} 3
Qcode.qseq the sequential number of the question, starting from 0 {gender.qseq} 5
Qcode.gseq the sequential number of the group, starting from 0 {gender.gseq} 1
Qcode.relevanceStatus whether the question is currently relevant (0 or 1) {gender.relevanceStatus} 1
Qcode.relevance the question-level relevance equation {gender.relevance} '!is_empty(name)'
Qcode.grelevance the  group-level relevance equation {gender.grelevance} 'num_children >= 5'
Qcode.sgqa the SGQA value for this question {gender.sgqa} '1827X3X337'

HTMLエディターの問題

  This issue is fixed after 2.05 build 140803


If you use HTML editor, some characters are replaced by HTML entities.

  • & by &amp;
  • < by &lt;
  • > by &gt;

If you use HTML editor you need to use :

  • and for &
  • lt for <
  • le for <=
  • gt for >
  • ge for >=

Qcode変数の命名

Here are the details of how to construct a Qcode (and access some properties) by question type.  In general, Qcodes are constructed as:

 QuestionCode . '_' . SubQuestionID . '_' . ScaleId

For comment and other, question code are QuestionCode_comment and QuestionCode_other

Type Description Code SubQs Answer Options Scales Answer Code Answer Shown Relevance
5 5 Point Choice Radio-Buttons Q1 1-5 {Q1} {Q1.shown} {Q1==3}
B Array (10 Point Choice) Radio-Buttons Q2 L1-L6 1-10 {Q2_L2} {Q2_L2.shown} {Q2_L2==7}
A Array (5 Point Choice) Radio-Buttons Q3 1-5 1-5 {Q3_1} {Q3_1.shown} {Q3_1>=3}
1 Array (Flexible Labels) Dual Scale Q4 sq1-sq5 0:a1-a3 1:b1-b3 {Q4_sq1_0} {Q4_sq1_1.shown} {Q4_sq1_1=='b2'}
H Array (Flexible) - Column Format Q5 1-5 s,m,t {Q5_1} {Q5_1.shown} {Q5_1=='s'}
F Array (Flexible) - Row Format Q6 F1-F5 1-5 {Q6_F3} {Q6_F3.shown} {Q6_F3==4}
E Array (Increase/Same/Decrease) Radio-Buttons Q7 1-7 I,S,D {Q7_4} {Q7_4.shown} {Q7_4=='D'}
: Array (Multi Flexi) 1 To 10 Q8 ls1,todo,ls2 min,max,avg {Q8_ls1_max} {Q8_ls2_avg.shown} {Q8_ls2_min==7}
; Array (Multi Flexi) Text Q9 hp,st,sw 1st,2nd,3rd {Q9_hp_3rd} {Q9_hp_3rd.shown} {Q9_hp_3rd=='Peter'}
C Array (Yes/Uncertain/No) Radio-Buttons Q10 1-5 Y,N,U {Q10_1} {Q10_1.shown} {Q10_3=='Y'}
X Boilerplate Question Q11 {Q11.shown}
D Date Q12 {Q12} {Q12.shown}
* Equation Q13 {Q13} {Q13.shown} {Q13>5}
~124~ File Upload (records number of files uploaded) Q14 {Q14} {Q14>0}
G Gender Drop-Down List Q15 M,F {Q15} {Q15.shown} {Q15=='M'}
U Huge Free Text Q16 {Q16} {Q16.shown} {strlen(Q16)>100}
I Language Question Q17 {Q17} {Q17.shown} {Q17=='en'}
! List - Dropdown Q18 1-5 {Q18} {Q18.shown} {Q18==3}
L List Drop-Down/Radio-Button List Q19 A-Z {Q19} {Q19.shown} {Q19=='X'}
O List With Comment Drop-Down/Radio-Button List + Textarea Q20 A-F {Q20},{Q20comment} {Q20.shown} {Q20=='B'}
T Long Free Text Q21 {Q21} {Q21.shown} {strstr(Q21,'hello')>0}
M Multiple Choice Checkbox Q22 A-F, other {Q22_E}, {Q22_other} {Q22_E.shown}, {Q22_other.shown} {Q22_E=='Y'}
P Multiple Choice With Comments Checkbox + Text Q23 A-F {Q23_D}, {Q23_Dcomment} {Q23_D.shown} {!is_empty(Q23)}
K Multiple Numerical Question Q24 self,mom,dad {Q24_self} {Q24_self.shown} {Q24_self>30}
Q Multiple Short Text Q25 A-F {Q25_B} {Q25_B.shown} {substr(Q25_B,1,1)=='Q'}
N Numerical Question Type Q26 {Q26} {Q26.shown} {Q26 > 30}
R Ranking Style Q27 1-4 {Q27_1} {Q27_1.shown} {Q27_1==3}
S Short Free Text Q28 {Q28} {Q28.shown} {Q28=='mine'}
Y Yes/No Radio-Buttons Q29 {Q29} {Q29.shown} {Q29=='Y'}

予約変数 this、self、that

Quite often, you want to evalute all parts of a question, such as counting how many sub-questions have been answered, or summing the scores.  Other times, you want to process just certain rows or columns of a question (such as getting the row or column sums and storing them in the database).  These reserved variables make that process relatively painless.

The 'this' variable is used exclusively within the "Whole question validation equation" and "Sub-question validation equation" advanced question options.  It expands to the variable names of each of the cells within those questions.  So, if you want to make sure that each entry is greater than three, you would set the "Sub-question validation equation" to (this > 3).

The 'self' and 'that' variable are more powerful, and serve as macros which are expanded prior to processing equations.  The syntax choices are:

  • self
  • self.suffix
  • self.sub-selector
  • self.sub-selector.suffix

suffix is any of the normal qcode suffixes (e.g. NAOK, value, shown)

sub-selector is one of:

  • comments - only subquestions that are comments (e.g. from multiple choice with comment and list with comment)
  • nocomments - only subquestions that are not comments
  • sq_X - where X is a row or column identifier.  Only sub-questions matching pattern X are selected. Note that search is done on complete code identifier, then sq_X match and include subquestions nX, X, Xn (e.g. if you use sq_1, subquestions a1, 1a, 1, 11 or 001 was included). Put attention at dual scale question type where subquestions code are QCODE_SQCODE_1 and QCODE_SQCODE_1 and to ranking question type where subquestions code are QCODE_1,QCODE_2 ....

Examples:

  • Has any part of a question been answered?  {count(self.NAOK)>0}
  • What is the assessment score for this question?  {sum(self.value)}

You can also use these to get row and column totals.  Say you have a array of numbers with rows A-E and columns 1-5.

  • What is the grand total?  {sum(self.NAOK)}
  • What is the total of row B?  {sum(self.sq_B.NAOK)}
  • What is the total of column 3? {sum(self.sq_3.NAOK)}

The 'that' variable is like the 'self' variable, but lets you refer to other questions.  Its syntax is:

  • that.qname
  • that.qname.suffix
  • that.qname.sub-selector
  • that.qname.sub-selector.suffix

qname is the question name without any sub-question extensions.  So, say you create a question 'q1', that is its qname

Examples:

  • Has any part of question q1 been answered?  {count(that.q1.NAOK)>0}
  • What is the assessment score for q2?  {sum(that.q2.NAOK)}
  • What is the grand total of q3? {sum(that.q3.NAOK)}
  • What is the total of row C in q4?  {sum(that.q4.sq_C.NAOK)}
  • What is the total of column 2 in q4? {sum(that.q4.sq_2.NAOK)}

The 'self' and 'that' variables can be used in any relevance,  validation, or tailoring.

The one caveat is that when you use the Show Logic File feature, it will show you the expanded value of 'self' and 'that'.  This lets you see the actual equation that will be generated so that you (and Expression Manager) can validate that the variables exist.  This may seem confusing since you may see quite lenghty equations.  However, if you edit the question, you will see the original equation using 'self' and/or 'that'

Also note that you should not use these variables if (a) you want to explicitly name each variable used in an equation, or (b) use variables that do not have sub-questions (e.g. single response questions).  In those cases, prefixing a variable with 'that' is overkill, and you run the risk of getting unexpected results.

NAOKの利用

NAOK --> "Not Applicable" (NA) is alright (OK)

Using NAOK, means that all or some of the variables are irrelevant (e.g. "Not Applicable" (NA) is alright (OK)).

When you put some variable from question in any equation : if this question (or subquestion) is hidden by condition : this disable all equation.

For example : count(Q1_SQ1,Q1_SQ2,Q1_SQ3,Q1_SQ4) give always an empty string if one subquestion of Q1 is filtered. To count the number of checked subquestion in such question can be count(Q1_SQ1.NAOK,Q1_SQ2.NAOK,Q1_SQ3.NAOK,Q1_SQ4.NAOK). If the sub question is hidden :Expression manager return an empty string.

Without NAOK : if one question or one subquestion is hidden : Expression Manager return always an empty string, same to return false.

The .shown always use the NAOK system (empty string if hidden) but if you need the code of the answer : it's always a good idea to add .NAOK after the question code. Except if you need it and know what you do.

Another example and information is provided at Overriding Cascading Conditions

関数へのアクセス

Expression Manager provides access to mathematical, string, and user-defined functions, as shown below.  It has PHP and JavaScript equivalents for these functions so that they work identically on server-side (PHP) and client-side (JavaScript).  It is easy to add new functions.

実装済み関数

The following functions are currently available:

Function Meaning Syntax
abs Absolute value number abs(number)
acos Arc cosine number acos(number)
addslashes Quote string with slashes string addslashes(string)
asin Arc sine number asin(number)
atan Arc tangent number atan(number)
atan2 Arc tangent of two variables number atan2(number, number)
ceil Round fractions up number ceil(number)
checkdate Returns true(1) if it is a valid date in gregorian calendar bool checkdate(month,day,year)
convert_value Convert a numerical value using a inputTable and outputTable of numerical values number convert_value(fValue, iStrict, sTranslateFromList, sTranslateToList)
cos Cosine number cos(number)
count count the number of answered (non-blank)questions in the list number count(arg1, arg12, ..., argN)
countif Count the number of answered questions in the list equal the first argument number countif(matches, arg1, arg2, ... argN)
countifop Count the number of answered questions in the list which pass the criteria (arg op value) number countifop(op, value, arg1, arg2, ... argN)
date Format a local date/time string date(format [, timestamp=time()])
exp Calculates the exponent of e number exp(number)
fixnum Display numbers with comma as radix separator, if needed string fixnum(number)
floor Round fractions down number floor(number)
gmdate Format a GMT date/time string gmdate(format [, timestamp=time()])
html_entity_decode Convert all HTML entities to their applicable characters (always uses ENT_QUOTES and UTF-8) string html_entity_decode(string)
htmlentities Convert all applicable characters to HTML entities (always uses ENT_QUOTES and UTF-8) string htmlentities(string)
expr_mgr_htmlspecialchars Convert special characters to HTML entities (always uses ENT_QUOTES and UTF-8) string htmlspecialchars(string)
expr_mgr_htmlspecialchars_decode Convert special HTML entities back to characters (always uses ENT_QUOTES and UTF-8) string htmlspecialchars_decode(string)
idate Format a local time/date as integer string idate(string [, timestamp=time()])
if Excel-style if(test,result_if_true,result_if_false) if(test,result_if_true,result_if_false)
implode Join array elements with a string string implode(glue,arg1,arg2,...,argN)
intval Get the integer value of a variable int intval(number [, base=10])
is_empty Determine whether a variable is considered to be empty bool is_empty(var)
is_float Finds whether the type of a variable is float bool is_float(var)
is_int Find whether the type of a variable is integer bool is_int(var)
is_nan Finds whether a value is not a number bool is_nan(var)
is_null Finds whether a variable is NULL bool is_null(var)
is_numeric Finds whether a variable is a number or a numeric string bool is_numeric(var)
is_string Find whether the type of a variable is string bool is_string(var)
join (New in 2.0 build 130129) Join elements as a new string join(arg1, arg2, ... argN)
list Return comma-separated list of non-blank values string list(arg1, arg2, ... argN)
log The logarithm of number to base, if given, or the natural logarithm. number log(number,base=e)
ltrim Strip whitespace (or other characters) from the beginning of a string string ltrim(string [, charlist])
max Find highest value number max(arg1, arg2, ... argN)
min Find lowest value number min(arg1, arg2, ... argN)
mktime Get UNIX timestamp for a date (each of the 6 arguments are optional) number mktime([hour [, minute [, second [, month [, day [, year ]]]]]])
modulo-function The modulo function is not supported yet. You can use the floor() function instead floor(x/y)==(x/y)
nl2br Inserts HTML line breaks before all newlines in a string string nl2br(string)
number_format Format a number with grouped thousands string number_format(number)
pi Get value of pi number pi()
pow Exponential expression number pow(base, exp)
quoted_printable_decode Convert a quoted-printable string to an 8 bit string string quoted_printable_decode(string)
quoted_printable_encode Convert a 8 bit string to a quoted-printable string string quoted_printable_encode(string)
quotemeta Quote meta characters string quotemeta(string)
rand Generate a random integer, see this example int rand() OR int rand(min, max)
regexMatch compare a string to a regular expression bool regexMatch(pattern,input)
round Rounds a number to an optional precision number round(val [, precision])
rtrim Strip whitespace (or other characters) from the end of a string string rtrim(string [, charlist])
sin Sine number sin(arg)
sprintf Return a formatted string string sprintf(format, arg1, arg2, ... argN)
sqrt Square root number sqrt(arg)
stddev Calculate the Sample Standard Deviation for the list of numbers number stddev(arg1, arg2, ... argN)
str_pad Pad a string to a certain length with another string string str_pad(input, pad_length [, pad_string])
str_repeat Repeat a string string str_repeat(input, multiplier)
str_replace Replace all occurrences of the search string with the replacement string string str_replace(search, replace, subject)
strcasecmp Binary safe case-insensitive string comparison int strcasecmp(str1, str2)
strcmp Binary safe string comparison int strcmp(str1, str2)
strip_tags Strip HTML and PHP tags from a string string strip_tags(str, allowable_tags)
stripos Find position of first occurrence of a case-insensitive unicode string (starting by 0, return false if not found) int stripos(haystack, needle [, offset=0])
stripslashes Un-quotes a quoted string string stripslashes(string)
stristr Case-insensitive strstr string stristr(haystack, needle [, before_needle=false])
strlen Get string length int strlen(string)
strpos Find position of first occurrence of an unicode string (starting by 0, return false if not found) int strpos(haystack, needle [ offset=0])
strrev Reverse a string string strrev(string)
strstr Find first occurrence of a string string strstr(haystack, needle[, before_needle=false])
strtolower Make a string lowercase string strtolower(string)
strtotime Parse about any English textual datetime description into a Unix timestamp int strtotime(string)
strtoupper Make a string uppercase string strtoupper(string)
substr Return part of an unicode string string substr(string, start [, length])
sum Calculate the sum of values in an array number sum(arg1, arg2, ... argN)
sumifop Sum the values of answered questions in the list which pass the criteria (arg op value) number sumifop(op, value, arg1, arg2, ... argN)
tan Tangent number tan(arg)
time Return current UNIX timestamp number time()
trim Strip whitespace (or other characters) from the beginning and end of a string string trim(string [, charlist])
ucwords Uppercase the first character of each word in a string string ucwords(string)
unique Returns true if all non-empty responses are unique boolean unique(arg1, ..., argN)

計画中・検討中の関数

Other functions that are planned (or being considered) but which are not implemented yet include the following.  Some of these are for backwards compatability with another survey tool.

Syntax Meaning Comments
e() returns the value of e
formatDate(X,PAT) return the string value of date X formatted according to Java data format pattern PAT
formatNumber(X,PAT) return the string value of number X formatted according to Java number format pattern PAT
getAnsOption(X) returns the text corresponding to the selected option for answer X this is the same as X.shown
getAnsOption(X,Y) returns the text corresponding to the option at index Y of node X
getRelevance(X) returns the relevance equation for question X
getStartTime() returns the date corresponding to the system time when the interview was started
getType(X) returns the string name of the datatype - e.g. *NA* if isNA()
gotoFirst() jumps to the first relevant set of questions - this violates the normal flow of the system
gotoNext() jumps to the next set of relevant questions - this violates the normal flow of the system
gotoPrevious() jumps to the previous set of relevant questions - this violates the normal flow of the system
isAsked(X) returns true if the answer is neither *NA*, *INVALID*, nor *UNASKED*
isInvalid(X) returns true if the answer is of type *INVALID*
isNA(X) returns true if the answer is of type *NA*
isNotUnderstood(X) returns true if the answer if of type *HUH*
isRefused(X) returns true if the answer is of type *REFUSED*
isSpecial(X) returns true if the answer is of type *UNASKED*, *NA*, *REFUSED*, *INVALID*, *UNKNOWN*, or *HUH*
isUnknown(X) returns true if the answer is of type *UNKNOWN*
jumpTo(X) jump to the group containing the named question -- this violates the normal flow of the system
jumpToFirstUnasked() jump to the first unasked question thus bypassing previous answered questions this violates the normal flow of the system
lastIndexOf(X,Y) returns the last index (base 0) of string Y in string X. Returns -1 if Y is not contained within X
list(X,...) a string containing a comma separated list of the positive values with "and" separating the last two
mean(X,...) returns the mean of a list of values
numAnsOptions(X) returns the number of answer options that question X has
orlist(X,...) a string containing a comma separated list of the positive values, with "or" separting the last two
parseDate(X,PAT) returns the date value of string X parsed with Java date format pattern PAT
parseNumber(X,PAT) returns the numerical value of string X parsed with Java number format pattern PAT
showAllResponsesExcept( questionList,attributeList,attributeTitleList) questionList = pipe-delimited list of question identifiers; attributeList = pipe-delimited list of attributes (like question#, title, text, type - so you can decide what to show); attributeTitleList = pipe-delimited list of table headers, so can internationalize the report.
showTheseResponses( questionList,attributeList,attributeTitleList) questionList = pipe-delimited list of question identifiers; attributeList = pipe-delimited list of attributes (like question#, title, text, type - so you can decide what to show); attributeTitleList = pipe-delimited list of table headers, so can internationalize the report.

式マネージャーとローカル変数

In order to properly build the JavaScript for page, Expression Manager needs to know which variables are set on the page, and what their JavaScript ID is (e.g. for document.getElementById(x)).  It also must know which variables are set on other pages (so that it can ensure that the needed <input type='hidden' value='x'> fields are present and populated).

カスケードされた条件

If any of the variables are irrelevant, the whole equation will be irrelevant (false).  For example, in the following table, N/A means that one of the variables was not relevant

Operator Example a b Result
+ (unary) +a N/A false
! !a N/A false
== (or eq) a == b N/A 5 false
== (or eq) a == b N/A 0 false
== (or eq) a == b N/A N/A false
!= (or ne) a != b N/A 5 false
!= (or ne) a != b N/A N/A false
!= (or ne) a != b N/A 0 false
> (or gt) a > b N/A 5 false
>= (or ge) a >= b N/A 5 false
< (or lt) a < b N/A 5 false
<= (or le) a <= b N/A 5 false
and a and b N/A 5 false
and a and b N/A N/A false
or a or b N/A N/A false
or a or b N/A 5 false
+ a + b N/A 5 false
* a * b N/A 5 false
/ a / b 5 N/A false
() (a) N/A false
(exp) (a && b) N/A 5 false
(exp) op (exp) (b + b) > (a && b) N/A 5 false
function sum(a,b,b) N/A 5 false
function max(a,b) N/A 5 false
function min(a,b) N/A 5 false
function implode(', ',a,b,a,b) N/A 5 false
function if(a,a,b) N/A 5 false
function is_empty(a) N/A false
function is_empty(a) 0 (or blank) true
function !is_empty(a) N/A false

カスケードされた条件の上書き

Say you want to show a running total of all relevant answers.  You might try to use the equation {sum(q1,q2,q3,...,qN)}.  However, this gets translated internally to LEMif(LEManyNA('q1','q2','q3',...,'qN'),,sum(LEMval('q1'),LEMval('q2'),LEMval('q3'),...,LEMval('qN'))).  So, if any of the values q1-qN are irrelevant, the equation will always return false.  In this case, the sum() will show 0 until all questions are answered.

To get around this, each variable can have a ".NAOK" suffix (meaning that Not Applicable is OK) added to it.  In such cases, the following behavior occurs.  Say you have a variable q1.NAOK

  1. q1 is not added to the LEManyNA() clause
  2. LEMval('q1') will  continue to check whether the response is relevant, and will return '' if it is not (so individual irrelevant responses will be ignored, but they will not void the entire expression).

So, the solution to the running total problem is to use the equation sum(q1.NAOK,q2.NAOK,q3.NAOK,...,qN.NAOK).

The use of the .NAOK suffix also lets authors design surveys that have several possible paths but then converge on common paths later.  For example, say subjects answer a survey in a way that is outside the normal range of responses.  The author could alert the subjects that they may not get valid results, and ask them whether they really want to  continue with the survey.  If they say Yes, then the rest of the questions will be shown.  The condition for the "rest of the questions" would check whether the initial responses were answered within the normal range OR whether the subject said Yes to the question that is only relevant if they answered outside the normal range.

式マネージャーはどのように条件付きカスタマイズを実現するか?

Here is an example of micro-tailoring (where Question Type=='expr' means an Equation):

Question Code Relevance Question Type Question
name 1 text What is your name?
age 1 text How old are you?
badage !is_empty(age) expr {(age<16) or (age>80)}
agestop badage message Sorry, {name}, you are too {if( (age<16),'young',if( (age>80),'old','middle-aged') ) } for this test.
kids !badage yesno Do you have children?
parents 1 expr {!badage && kids=='Y'}
numKids parents text How many children do you have?
kid1 parents && numKids >= 1 text How old is your first child?
kid2 parents && numKids >= 2 text How old is your second child?
kid3 parents && numKids >= 3 text How old is your third child?
kid4 parents && numKids >= 4 text How old is your fourth child?
kid5 parents && numKids >= 5 text How old is your fifth child?
sumage 1 expr {sum(kid1.NAOK,kid2.NAOK,kid3.NAOK,kid4.NAOK,kid5.NAOK)}
report parents yesno {name}, you said you are {age} and that you have {numKids}.  The sum of ages of your first {min(numKids,5)} kids is {sumage}

All of these questions can be on a single page (e.g. in the same group), and only the relevant questions will display.  Moreover, as you enter the ages of children, the sum() expression in the last question will dynamically update on the page.

Expression Manager provides this functionality by surrounding each expression with a named <span> element.  Every time a value changes, it recomputes the expression that should appear in that <span> element and regenerates the display.  You can have dozens, or even hundreds, of such tailored expressions on the same page, and the page will re-display all of them in a single screen refresh.

LimeSurvey 1.91と式マネージャー機能の対照表

Old Feature New Feature Comments
Conditions Relevance You can use very complex conditional equations, and access a broader range of variables
Assessments Equation Any assessment scores can be re-structured into an Equation. This both ensures that the score is written to the database, and also lets you see dynamic changes to the score value on the current page
Replacements Expression Manager The core engine takes the input string and treats everything within curly braces as an Expression - so it handles all historical replacements types.  To avoid messing up embedded JavaScript, Expression Manager only processes content between curly braces as long as (a)  there is no leading or trailing whitespace within the curly braces - e.g. {expr} is an expression, but { expr}, {expr }, and { expr } are not expressions.  Furthermore, Expression Manager does not process content within its own strings (e.g. {list('hi','there {braces}')} generates "hi there {braces}").  It also ignores escaped curly braces (e.g. \{this is not an expression\})
Validation Expression Manager The plan is to take the current min/max Question Attributes and have Expression Manager process them.  That way the min/max values can be expressions themselves

構文ハイライト

To help with entering and validating expressions, EM provides syntax highlighting with the following features:

構文ハイライトの種類と意味

Color Sample Meaning Tooltip Comments
tan background Sample the whole equation none Anything within curly braces that is recognized as an equation (e.g. there is no leading or trailing whitepace) will be color-coded with a tan background to help distinguish it from surrounding text
bold red text Sample An error Some explanation on error Can be an unknow variable or an error in function, .... Survey can be totally broken, this don't show to public user.
blue text Sample function name meaning and allowable syntax function names, or things that should be functions since they are followed by an opening parenthesis, are presented in bold blue text. Tooltips show the meaning and allowable syntax for the function.
grey text Sample string none single and double-quoted strings are shown in grey text
cyan text Sample variable set on the same page, [name or SGQA code]: question; value; answerList showing codes for each value Any variable that is set on the same page to the current question is shown in cyan text, showning it can be updated in javascript. The tooltip shows its name (if you used INSERTANS:xxx) or SGQA code (if you used the new naming system), the actual question, and its current value (or blank if not set). If the question type expects responses from an enumerated value set, the mapping of the codes to display values is show.
green text Sample variable set on a prior page [name or SGQA code]: question; value; answerList showing codes for each value Any variable that is set on a prior page is shown in bold green text. The tooltip shows its name (if you used INSERTANS:xxx) or SGQA code (if you used the new naming system), the actual question, and its current value (or blank if not set). If the question type expects responses from an enumerated value set, the mapping of the codes to display values is show.
bold pink text Sample variable set on a later page in general : empty at survey start, but can be filled with index or move previous [name or SGQA code]: question; value; answerList showing codes for each value Any variable that is set on a prior page is shown in bold pink text. The tooltip shows its name (if you used INSERTANS:xxx) or SGQA code (if you used the new naming system), the actual question, and its current value (or blank if not set). If the question type expects responses from an enumerated value set, the mapping of the codes to display values is show.
bold tan text Sample a lime replacement value the value Lime Replacement Strings (like {TOKEN:xxx}, {PRIVACY_MESSAGE}) are shown in bold tan text.
red text Sample assignment operator (=) warning message If you use one of the assignment operator (=) that operator will be displayed in red text. This is meant to help prevent accidental re-assignment of values when you really meant to check whether a == b instead of setting the value of a = b.
normal black text Sample punctuation none All other punctuation within the expression is shown as normal black text.
red-boxed text a bold red line surrounds the error syntax error description of the error Any detected syntax errors are shown by surrounding the error with a red box. The tooltip shows the error. Examples include unmatched parentheses, use of undefined functions, passing the wrong number of arguments to functions, poorly structured expressions (e.g. missing operators between variables), trying to assign a new value to a read-only variable, trying to assign values to non-variables, or using unsupported syntax. Note that the syntax error dectection system may only report one error in an expression even if there are multiple errors; however, if any errors are detected, at least one error will be shown.

参考記事

式マネージャーのサンプル

ユースケースとHowTo

ステップバイステップの例

開発者向け参考情報

ロードマップ/状況/ToDoリスト