0

I need to create dichotomic fields based on a single field which shows multiple choice answers in the form of strings separated by a space. What I want to do is this:

enter image description here

The number of choices that will produce the new fields is known, but I have 27 fields with data from multiple choice questions in several layers, I know how to do this manually, but it would take a very long time.

update: Here is a screenshot of one of my field of interest, there are blank spaces, there are no "0" because the multiple-choice options begin with "1". When in a group this field is not filled (because it depends on previous selections) then it becomes blank.

enter image description here

1 Answer 1

1

You can create the fields with an expression such as below. For example, create FIELD_1 with expression

if(array_contains(string_to_array(data, ' '), 1), 1, 0)

The expression looks at a field data and if it contains 1 returns 1 otherwise 0. You can repeat the process for all the fields you need to create.

As your problem requires you to repeat this multiple times, you can use a little bit of pyqgis to automate it. Select the layer containing the data. Open a python console in QGIS with the layer selected and copy/paste the following code and hit Enter. change num_choices to number of fields you require and data with the field containing the data.

layer = iface.activeLayer()
num_choices = 5
for x in range(1, num_choices+1):
  field = QgsField( 'FIELD_{}'.format(x), QVariant.String )
  idx = layer.addExpressionField("if(array_contains(string_to_array(data, ' '), {}), 1, 0)".format(x), field)

For a test layer with your test data, I get the following output in QGIS3.4

enter image description here

1
  • Hi! for some reason when I update the field name in the console, whether I use "or not, It doesn´t seem to update, so I figure out that updating the field name in the layer properties does what I need. So this is definitely the right solution. Commented Sep 6, 2019 at 4:16

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Not the answer you're looking for? Browse other questions tagged or ask your own question.