Actions

Preguntas condicionadas o ramificación

From LimeSurvey Manual

Revision as of 07:24, 5 September 2023 by Maren.fritz (talk | contribs) (Created page with "* Mostrar pregunta 'Alcohol' '''si''' "el 'DrinkingHistory' atributo del participante" coincide con la cadena 'Sí'. ** ''valor probado''= el...")


Vistazo a las Condiciones en LimeSurvey

LimeSurvey tiene una función de ramificación lógica muy poderosa. Se puede acceder haciendo clic en el botón Establecer condiciones - Archivo:conditions_icon.png - ubicado en cada barra de preguntas.

En este capítulo describiremos:

  • qué condiciones puede encontrar en LimeSurvey
  • qué puede y no puede hacer con las condiciones
  • qué pasos debe aprender para configurar condiciones simples o más complejas

Para obtener instrucciones en video paso a paso, consulte este tutorial o descargue la encuesta de muestra de condición: [[Media:LimeSurvey_Survey_Setting_Conditions.zip|LimeSurvey_Survey_Setting_Conditions.zip] ].


 Hint: Las funcionalidades de condiciones funcionan como una GUI para las expresiones y ecuaciones que se pueden aplicar a las preguntas, permitiendo a los usuarios aumentar fácilmente la complejidad de sus encuestas sin entrar en expresiones y relevancia. ecuaciones. Sin embargo, el ExpressionScript debe ser estudiado/conocido para aumentar la gama de opciones disponibles dentro de LimeSurvey.


Ocultar/Mostrar ramificación frente a salto de ramificación

Tú puedes diseñar ramificaciones lógicas con LimeSurvey, esto significa que puedes decidir qué preguntas serán mostradas si y solo si algunas condiciones son cumplidas, de la forma "Mostrar Pregunta X si la Pregunta Y tuvo una respuesta Z".

Nuestro enfoque es implementar una Ocultar/Mostrar lógica de ramificación:

  • puede definir una condición o un conjunto de condiciones en cada pregunta de su encuesta; si se cumple la condición, la pregunta será entonces desplegado:



En pocas palabras:
  • una pregunta sin una condición definida siempre se mostrará;
  • una pregunta con una condición definida no se mostrará a menos que se cumpla la condición .

Este enfoque es diferente de la Lógica de ramificación de salto que a veces implementa otro software. En la Lógica de ramificación de salto, la acción resultante de una condición cumplida sería saltar a otra pregunta (es decir, ocultar todas las preguntas intermedias). LimeSurvey no implementa este método Jump Branching Logic. En cambio, si desea omitir una serie de preguntas, simplemente debe establecer la misma condición en todas las preguntas que no desea que se muestren. Por ejemplo, si la condición de salto que desea establecer en la Pregunta 2 es "Saltar a la Pregunta 5 si la respuesta a la Pregunta 1 es 'Sí'", simplemente puede:

  • establecer una condición en las preguntas 2, 3 y 4 para mostrar solo "si la respuesta a la Pregunta 1 fue NO 'Sí'"

LimeSurvey facilita el establecimiento de la misma condición en múltiples preguntas (y por lo tanto implementa Lógica de ramificación de salto) al permitirle "copiar" una condición de una pregunta a una serie de otras. En el ejemplo anterior, comenzaría estableciendo la condición en la Pregunta 2 y luego, desde la misma pantalla, copiaría esa condición en la Pregunta 3 y la Pregunta 4.

Para obtener más detalles sobre cómo copiar condiciones dentro de LimeSurvey, continúe leyendo la siguiente sección wiki.


Tipos de condiciones admitidos

Básicamente, una condición puede comparar valores y devolver verdadero o falso.

Los valores que se pueden comparar son respuestas a preguntas anteriores. Por ejemplo, si responde "Sí" a la Pregunta 1, la Pregunta 2 se mostrará al encuestado:





En este punto, es importante comprender qué se considera una entrada de pregunta elegible para el editor de condiciones.

Una entrada de pregunta es:

  • una pregunta simple (para todos los tipos de preguntas excepto las preguntas de matriz)
    • por ejemplo: preguntas de texto, listas desplegables o de radio, e incluso opciones múltiples ¡preguntas
  • o una fila en Preguntas de matriz (excepto para la escala dual de matriz y las preguntas flexibles múltiples de matriz)
    • por ejemplo: matriz con 5 botones de opción o matriz con preguntas de etiqueta
  • o la parte izquierda o la parte derecha de una pregunta de doble escala de Array
  • o cada celda de una pregunta de Array flexible

Template:Nota

  • valores constantes
    • por ejemplo: "Si respondió hace más de 18 años a la siguiente pregunta"



  • Datos del perfil de los participantes: Para utilizar datos de la tabla de participantes de la encuesta, "Respuestas anónimas" se debe configurar en NO. Esta opción se puede encontrar en el panel configuración del participante de la encuesta.





Se admiten varios operadores de comparación, desde el simple "igual" hasta la avanzada "expresión regular":

  • ¡Los básicos se refieren a las operaciones "igual" y "no igual a"
  • El mayor/menor La familia de operadores than también está disponible y generalmente se usa cuando se usan entradas de preguntas numéricas. ¡N!** Tenga en cuenta que las comparaciones en campos numéricos utilizan el orden numérico. Por ejemplo, 2 < 10
    • Si está utilizando una entrada de pregunta cuyo tipo es texto, la condición podría evaluarse como "2" > "10" (orden de cadena)!
    • Preguntas numéricas, así como las preguntas de texto (cuando tienen el atributo 'numbers_only' establecido), usarán el orden numérico para las comparaciones. ¡N!* También está disponible un operador de comparación avanzado que usa expresiones regulares (¡no entre en pánico! Si no lo sabe qué significa esto, entonces no lo necesita)
    • el patrón no debe estar encerrado entre caracteres '/'
    • por ejemplo: [a-zA -Z]$


¿Cómo puedo combinar condiciones?

Puede construir condiciones complejas combinando condiciones simples con los operadores lógicos AND y OR .



Sin embargo, es importante comprender que LimeSurvey determina automáticamente qué operador lógico aplicar. Esto significa que el uso de los operadores OR o AND se determina según el contexto de la condición. En el ejemplo anterior, sólo hay un escenario. Esto significa que LimeSurvey utiliza Álgebra booleana, lo que significa que el operador o se "calcula" primero.

Hablaremos más sobre condiciones complejas más adelante. Centrémonos primero juntos en los elementales.

El diseñador de condiciones

Primero, debe acceder al diseñador de condiciones. Para hacer eso, haga clic en la pregunta a la que desea aplicar la condición:



Ahora, busque el botón Establecer condiciones ubicado en la barra de preguntas superior:



Una vez accedida, se mostrará la siguiente página:



El panel del diseñador de condiciones se puede dividir en tres secciones:


La barra de herramientas del diseñador de condiciones

Puede encontrar en la barra de herramientas las siguientes opciones:



  • Mostrar condiciones para esta pregunta: Haga clic en este botón para obtener una descripción general rápida de las condiciones existentes actualmente que se aplican a su pregunta.
  • Agregar y editar condiciones: Representa la página predeterminada que se abre automáticamente una vez que haces clic en el botón Establecer condiciones. Está dividido en dos partes: (1) una tabla que muestra todas las condiciones y escenarios existentes, y (2) el menú agregar/editar condiciones.
  • Condiciones de copia: A veces, desea aplicar la misma condición a X preguntas para que la pregunta Y se muestre al final. Para ello haga clic en Copiar condiciones. Se abrirá una nueva ventana que muestra las condiciones existentes actualmente agregadas a su pregunta (llamémosla pregunta 3). Para agregarlas a la pregunta 5, marque las condiciones que desea copiar, seleccione la pregunta 5 y haga clic en el botón Copiar condiciones ubicado en la parte inferior izquierda del panel. Para obtener más información, continúe leyendo la siguiente sección wiki.
  • Guardar y cerrar: Una vez que haya terminado con los cambios, haga clic en Guardar y cerrar para guardar sus condiciones.
  • Mover a pregunta: Para no salir del panel del diseñador de condiciones mientras pasa a otra pregunta, use la siguiente opción para seleccionar de la lista desplegable la siguiente pregunta a la que desea aplicar condiciones. Tenga en cuenta que la lista desplegable muestra las preguntas que se muestran en la encuesta antes y después de la pregunta actual.
  • 'Cerrar: Si desea salir del panel sin realizar ningún cambio, puede ir directamente a la pestaña de configuración/estructura y seleccionar la opción deseada o hacer clic en Cerrar, que se encuentra en la parte superior derecha de la pantalla.


Resumen de las condiciones existentes

Esta sección muestra una tabla que contiene todos los escenarios y condiciones existentes de una pregunta. Ciertas acciones se pueden realizar desde aquí:



  • En la parte superior derecha, hay tres acciones disponibles:
    • Agregar condiciones rápidamente: acelera el proceso de agregar condiciones (lea a continuación para conocer todas las opciones )
    • Renumerar escenarios: si se hace clic, los escenarios se renumerarán con números incrementales comenzando desde uno. Tenga en cuenta que esta opción se muestra solo si se aplican dos o más escenarios a su pregunta.
    • Eliminar todas las condiciones: puede eliminar mediante esta acción todas las condiciones y escenarios existentes actualmente aplicados a su pregunta.



  • Además del número de identificación de cada escenario, hay tres botones que le permiten realizar las siguientes acciones:
    • Eliminar escenario
    • Cambiar número de escenario
    • Agregar condición a este escenario - haga clic en esto botón para agregar otra condición al escenario deseado



  • Se pueden realizar dos acciones en cada condición:
    • Eliminar condición
    • Editar condición: si hace clic, podrá editar la condición desde el menú condiciones


Agregar/Editar condiciones

La parte inferior de la pantalla está asignada al menú Agregar/editar condiciones:



También puedes editar la condición desde la misma ubicación si presionaste antes en el lápiz verde que corresponde a la pregunta que deseas editar (ver la tabla de condiciones y escenarios).

Para comprender cómo funciona la función de condiciones en LimeSurvey, primero presentaremos las condiciones elementales.


Nota: Por el momento no modificar el escenario predeterminado () que se selecciona automáticamente en el formulario de adición de condiciones. Se tratará más adelante en esta sección wiki.


Definición de condiciones elementales

Una condición elemental es simplemente una condición única sin operadores lógicos OR o AND.

Está compuesto por:

  • un operando izquierdo: el valor probado. Puede elegir el tipo valor probado seleccionando la pestaña correspondiente en el editor de condiciones. Puede ser una pregunta anterior o un atributo participante de la encuesta.



Si selecciona una entrada de pregunta (de la pestaña Preguntas anteriores) y si esta pregunta utiliza respuestas predefinidas, las respuestas predefinidas correspondientes se muestran en la pestaña Predefinida de la selección de valores de comparación. .


Tenga en cuenta que para utilizar el Token su encuesta debe:


  • un operador de comparación. Elija el operador de comparación que desea aplicar de la lista desplegable (menor que, menor o igual a, igual, no igual a, mayor o igual a, mayor que, expresión regular).


  • un operando derecho: el valor de comparación. Puede elegir el tipo valor de comparación seleccionando la pestaña correspondiente en el editor de condiciones. Cuando crea una condición, puede seleccionar como valor de comparación un valor predefinido (respuesta), una constante, una pregunta, un atributo de un participante de la encuesta o una expresión regular:


Ejemplo de condiciones elementales y cómo crearlas

  • Mostrar pregunta 'AAMN' si "la respuesta a la pregunta 'Género' es la respuesta predefinida 'Masculino'"
    • valor probado = respuesta a la pregunta 'Género'
** operador de comparación = es igual
    • valor de comparación = código de respuesta predefinido (la respuesta 'Masculino' en este caso)



  • Mostrar Pregunta 'Alcohol' si "la respuesta a la Pregunta 'Edad' es mayor o igual que el valor numérico '18'"
    • valor probado = respuesta a la Pregunta 'Edad '
    • operador de comparación = mayor o igual que
    • valor de comparación = el valor constante '18'



  Atención : Cuando utilice un 'valor de comparación' constante para una pregunta de fecha, independientemente del formato de fecha establecido en su encuesta, debe usar el formato de fecha AAAA-MM-DD.



  • Mostrar pregunta 'Alcohol' si "la respuesta a la pregunta 'Fecha de nacimiento' es mayor que 2000-01-01"
    • valor probado = respuesta a la pregunta 'Fecha de nacimiento' '
    • operador de comparación = Mayor o igual que
    • valor de comparación = '2000-01-01' (el formato en el campo constante: 2000-01-01 )




Conditions and scenarios in LimeSurvey

Default condition combinations

As said earlier, LimeSurvey automatically decides which logical operator (AND or OR) should be applied between conditions depending on the 'context'.

Note also that the order in which you define your elementary conditions is not relevant as LimeSurvey will automatically reorder them according to its own logic.

Let's study this in detail. Two rules should be always remembered:

  • First rule: conditions having the same tested value are ORed together
  • Second rule: conditions having different tested value are ANDed together


First rule: conditions having the same tested value are ORed together

When you have several conditions, they are ORed together if they share the same tested value. This is the case if the condition applies to several answers belonging to one single question. For example, a condition was applied below to three answers belonging to the same question - if answer to Question 'FavColour' equals 'green' OR  answer to Question 'FavColour' equals 'red'  OR  answer to Question 'FavColour' equals 'blue', then Question 'BirthDate' will be displayed to the survey respondent:



Note: To select multiple predefined answers, don't forget to hold the Shift or Ctrl key while selecting the tested values.


Second rule: conditions having different tested value are ANDed together

When you have several conditions, they are ANDed together if they don't share the same tested values. For example, you may see below the case for several conditions based on different previous questions - "If answer to Question 'Alcohol' equals 'Y' answer AND answer to Question 'Gender' equals 'F'", then Question 'Alcoholconsumption' will be displayed to the survey respondent:



The multiple options questions

Note: This paragraph applies to Multiple options and Multiple options with comments questions, and not to Array Multiple Flexible (number) with checkbox layout questions (in case of the latter, each checkbox is a separate question-entry and is not really handled as other multiple options question-types).


The Multiple choice and Multiple choice with comments question types will be displayed in two flavors:

  • a Group of checkboxes flavor which let you set conditions on all possible answers of the respective question;
  • a set of Single checkbox entries which lets you set conditions on each checkbox individually.



The group of checkboxes flavour

Now, let's focus on an example to better understand the difference between the two flavours. Let's imagine that we wish to display the 'Pointchoice' Question only if the respondent checks at least one of the tested answers listed under the 'MultipleOrganizations' Question.

As mentioned above, the group of checkboxes flavor allows you to set conditions on all possible answers of the respective question. Therefore, only the options that refer to responsibilities are selected as comparison values below:



As we can observe, the conditions get ORed due to the Group of checkboxes flavour selected in the beginning.:



ANDing conditions in multiple choice questions

Now, let's focus on a similar example. However, we are looking this time only for the most active members to ask them further questions. To do this, we make use of the Single checkbox flavour which allows you to set conditions based on each checkbox individually.

In this example, question X will be displayed if A and B are checked:



Once done, you can observe that the two conditions are ANDed now.



This means that your question will not be displayed unless both tested values (the selected subquestions) are met.


The usage of scenarios - Using ORed conditions between different questions

Now, you may argue that sometimes you need to have ORed conditions even when they are set on different questions (that is to say on different tested values). This is why we got scenarios!


Definition of a scenario

A scenario is simply a manual grouping of conditions in which some conditions are evaluated independently of other conditions from other scenarios. The complex condition resulting in this association of several scenarios will be met only if one scenario is met. In other words, scenarios are logical grouping of conditions, respecting the above rules, and which are ORed together to build complex conditions.

Everything described above applies to the conditions located in every scenario. By default, all the new conditions are created inside the Default Scenario, which uses number '1' as its identifier. When you create new conditions, you can choose whether they are added to the default scenario or not. To change the scenario, just use another identifier.


Adding a question to another scenario

When you create (or edit) a condition, you can modify the scenario in which the condition is stored by simply clicking on the add scenario button:



As you can observe, the default scenario uses as identifier '1'. To add conditions to different scenarios, change the identifier by typing a different number in the box.

The number id of a scenario has no importance and different scenarios can have non-continuous ids.



You can change the number assigned to a scenario by clicking this Icon and assigning the new id to the scenario.



Note: As said above, scenario numbers have no impact in the way conditions are evaluated. However, modifying the scenario numbers are needed in order to:
  • decide in which order the scenarios are displayed when using the printable version of a survey
  • merge conditions from two scenarios (in order to merge scenario 10 with scenario 1, just renumber scenario 10, so that it is scenario 1).


Example: creating three scenarios

To create three scenarios, you need at least three conditions and to add to each of them a different scenario id. Once done, the scenarios are going to be connected among themselves via the 'OR' operator. For example, it could look like this:


AND vs OR in the same scenario

You may end up in certain cases with AND and OR logical operators in the same scenario:



LimeSurvey will always apply first OR. For further details on this, you may check the following Wikipedia article on Boolean algebra.

However. the order of operations can also be observed in the Relevance equation field. For the above example, the relevance equation is highlighted below:



As it can be observed, a set of extra parentheses is added for the OR logical operations in order to let the software know that it must be "computed" first.


Help: For more information on relevance equations, check the ExpressionScript - Presentation and relevance equation wiki sections.

How to copy conditions

The copy conditions functionality can be used when you wish to apply the same set of conditions you applied to Question5 to Question10. In this way, you will not have to manually recreate the conditions you applied to the previous question(s).

To start copying conditions, you first have to select the question the condition(s) is/are applied to (Question 'LowQ' in our case). Then, select the conditions you wish to be copied and select the question you wish to have the conditions added to (Question 'Alcohol' in our case).



Note: Conditions can only be set based on questions that appear before the question on which the condition is set.

Please pay attention to how the copy conditions functions work when you wish to copy and apply a set of conditions located under different scenarios to another question which uses the same or different scenario id numbers. To summarise the possible cases you might have, check the following example:

  • you wish to copy Scenario 1 - Condition A, Scenario 1- Condition B, Scenario 7 - Condition C, and Scenario 7 - Condition D from QuestionX into QuestionY
  • QuestionY already contains Scenario 1 - Condition A, Scenario - Condition C, Scenario 6 - Condition E, Scenario 8- Condition F.
  • Once copied, the following conditions will be applied to QuestionY:
    • Scenario 1: Condition A, Condition B, Condition C -> Condition A is not copied anymore as it already exists in QuestionY, only condition B being copied.
    • Scenario 6: Condition E -> not affected
    • Scenario 7: Condition C, Condition D -> a new scenario is created where the two conditions are added to it
    • Scenario 8: Condition F -> not affected


Reset conditions

To quickly reset all the survey conditions, click on one survey-related setting, look for Tools on the top toolbar, and click Reset conditions:



Next, confirm on the next page that you want to proceed and all the conditions will be deleted.


Things to watch out for

General considerations

There are a few basic rules you should keep in mind before setting conditions on a question:

  • Once a single condition has been set for a question, that question will not be displayed unless that condition is met.
  • Conditions can only be set based on questions that appear before the question on which the condition is set.
  • If you change the order of questions in your survey after you create conditions, LimeSurvey does not warn you if the changed order will break any of your conditions. You should always put aside the creation of conditions until you are satisfied with the order of questions and groups in your survey.
  • You can modify conditions even after a survey has been activated. This should be done with caution, as there is no "consistency checking" applied here.


Conditions using the 'no answer' predefined answer


Setting the following condition "Show question 'FavColour' if the answer to the question 'Gender' is 'no answer'" really means "show question 'FavColour' if question 'Gender' was displayed to the survey participant who did not submit answer".


 Hint: To have the no answer option displayed as a predefined answer, the question cannot be mandatory.


Chained conditions

If you set conditions on a question that, itself, has conditions, you could end up with your survey behaving in ways you might not have predicted. For example, a typical side-effect is that if you hide all questions in a group with chained conditions, the group header will still be shown unless you correct these conditions as explained below.




In the above example, the 'Alcohol' question is displayed if the respondent has previously answered to the 'AAMN' question 'No (N)'. However, the 'AAMN' question might not be displayed at the end if the respondent did not select to the previous question ('Gender') answer 'Male (M)'. In this scenario, no 'Alcohol' question will be displayed if 'Male (M)' was chosen previously.

To have the 'Alcohol' question displayed, you have to copy the conditions from the earlier question(s) to the one you're editing. To have the 'Alcohol' question displayed, you need to set up the following set of conditions:

  • Show 'AAMN' if the answer to 'Gender' is 'Male (M)'
  • Show 'Alcohol' if answer to 'Gender' is 'Male (M)' and if answer to 'AAMN' is No (N)'.

After correction, the correct set of conditions for 'Alcohol' should look like this:



So if you are designing a complicated survey with a large number of conditions, make sure you test the survey for as many different combinations of results as you can think of.

To find out more on how you can copy conditions in LimeSurvey, please scroll up or click here to continue reading the dedicates wiki section.


Limitations and workarounds

Progress-bar

If you create a survey where many questions get skipped because of conditions, the progress bar either jumps over a set of questions or the survey ends at 50%.

To avoid such behavior, the questions that could be skipped should be arranged between the shown questions. In this way, only one or two questions get skipped per answer.

For example, based on Question1 (yes or no question), 14 questions (2A to 15A) will be displayed if the answer to Question1 is 'Yes', or 2B to 15B if the answer to Question1 was 'No'.

If you arrange the questions in one group and arrange them like 2A, 2B, 3A, 3B, and so on, you will get a nearly correct progress bar, while arranging the questions like 2A, 3A, 4A, [...], 2B, 3B, 4B, ... you will get a progress bar from 0 to 50% or from 50% to 100%, depending on the answer to the first question.


Setting a constant comparison value for a "Date" Question Type

You have to use the internal representation of Date values (which is YYYY-MM-DD) to define your constant comparison value.


Setting conditions for "Other" Options in the Multiple Options Question Type

In the multiple options question type, you can use the "Other" provided in the question type as a valid choice but you cannot set conditions on it. For example, Question No 1 says "Which color do you prefer to use?" Answer checkbox choices are Blue, Black and Other. If the participant chooses Blue, you can set a condition. If the participant chooses Black, you can set a different condition. However, if the participant chooses "Other" and types in something in the text box, there is NO way a condition can be set. LimeSurvey does not recognize if the participant chose the "Other" condition. This is NOT a bug but a limitation.

There is no real field recorded for the 'other' checkbox for this question type. Thus, the only way to know if the user has answered the 'other' part of the question or not would be to check if the value of the text written in the other input field is empty or not.

However, due to the specific way Multiple choice questions are handled, testing the 'other' text input field has never been implemented.

As a workaround, add an explicit answer option called 'Other' and do not use the built-in 'other' option of these question types. Then add an additional short text question which will be displayed if this 'Other' checkbox was clicked.


How to use parenthesis for the boolean expressions?

You can't!

If you want to design something like:

(condition1 OR condition2) AND (condition3 OR condition4),

you'll have to set up:

 (condition1 AND condition3) OR

 (condition1 AND condition4) OR

 (condition2 AND condition3) OR

 (condition2 AND condition4)