QGIS Field Calculator – Use Field Calculator QGIS: If Value in One Column, Then Value in New Column

calculate-valuesfield-calculatorqgis

I am having troubles using the field calculator to get what I want.
One column in my attribute table is named 'Taxa' and has a set of species in it. Species are separated by #.

I want to make a new column using the field calculator that returns a value, based on the species in the 'Taxa' column.

An example of the column I want to use to calculate a value in the new column:
'Taxa' column example
Below i have some examples of values per species:

Calluna_vulgaris =1
Baeomyces_rufus = 1
Porpidia_crustulata =2
Rhizocarpon reductum =2
Micarea_erratica = 2
Hypnum_jutlandicum = 1/3

To summarize: If the Taxa column says 'Calluna_vulgaris#Porpidia_crustulata#Micarea_erratica'

I want the new column to have the number 5.

I understand this is not the most convenient way to group species in a column, but I used the TomBio addon which does this automatically.

Best Answer

You can use regexp_match function to find starting position of the word within the string. Than with using condition if you can test if there is string occurence (e.g. starting position > 0) and set the value for TRUE (your value) and FALSE (0).

It should look like this:

if(regexp_match(taxa, 'Calluna_vulgaris')>0,1,0) +
if(regexp_match(taxa, 'Porpidia_crustulata')>0,2,0) +
if(regexp_match(taxa, 'Rhizocarpon reductum')>0,2,0) +
if(regexp_match(taxa, 'Micarea_erratica')>0,2,0)

enter image description here

Maybe there is better regexp solution, but I'm not so regexp ninja.

Related Question