4

I am trying to create a new field in QGIS where:

  • if the number in the field "DN"=2, then the new field (a text string) will say "veg"
  • and if the number in the field "DN"=1, then the new field will say unveg.

I have tried creating a new field and using the replace function, I have tried an if, then function, but I can't seem to get it to work. I am just trying to create an unvegetated to vegetated ratio and am having immense trouble with this simple step and feel very stuck.

Can you offer advice?

1
  • I just saw that you chose the 289 reputation point answer over the 17,000 reputation point answer. I can only advise you to take a closer look at J.R.'s answer and accept it. This is the correct way to handle the data. Anything else is just error-prone and time-consuming fiddling around.
    – Bernd V.
    Commented Oct 1 at 4:27

2 Answers 2

11

If your "DN" field has only the two values 1 and 2 you may use the conditional function if:

if(condition, result_when_true, result_when_false)

In your case:

if("DN"=2, 'veg', 'unveg')

or alternatively:

if("DN"=1, 'unveg', 'veg')

But this will return 'unveg' all the time that "DN" is not equal to 2, and not only when it's equal to 1 (or the opposite if you use the alternative option)

It may be safer to use the conditional function CASE: CASE WHEN condition THEN result ELSE END that let you add a third option (the ELSE part) for when "DN" is not equal to 1 or 2

CASE
   WHEN "DN"=2 THEN 'veg'
   WHEN "DN"=1 THEN 'unveg'
   ELSE 'DN not equal to 1 or 2'
END
4

Presumably if the field already has values like 1 and 2 it's an integer field (or is this a text field with numbers as strings?), and I don't expect you'll be able to just substitute string values into an integer field. Perhaps others know better. Anyway, my solution would be this:

  1. Create a new empty text field.
  2. Use 'Select by attribute' to choose the records from the first field that have a value of 1.
  3. In the attribute table or field calculator, mass edit all selected records of the new text field to have the value 'unveg'
  4. Invert the selection so now all records with a value of 2 will be selected. This assumes the field only has values of 1 or 2.
  5. Perform step 3 again, this time mass editing all selected records in the new text field to have the value 'veg'

Try that out and see if that works for you.

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.