Thursday, 16 August 2018

Using if statement in R script within QGIS


I am creating an R script in QGIS and I am facing an issue with an if statement. First, I declare the input from the user


##Which_S2_bands_do_you_want_to_use=selection 2 3 4 5 6 7 8 11 12;2 3 4 8 11 12

Later I use it in the following condition:


if (Which_S2_bands_do_you_want_to_use == "2 3 4 5 6 7 8 11 12") {

bands<-c("B((0[2348]_10m)|(((0[567])|(1[12])|(8A))_20m)).jp2$")}

And use it in the following code:


  S2<-list.files(S2, recursive = TRUE, full.names = TRUE, pattern=bands)

When I run it, I get the following error:


Error in list.files(S2, recursive = TRUE, full.names = TRUE, pattern = bands) :
object 'bands' not found
Execution halted


It seems the if statment is not been run. Any idea what could be the reason?


Maybe another approach to use the input from the user as a condition to change a variable in the script?



Answer



With the new R processing provider, when you give the user selection options, the options are returned as integers starting with 0 (Python indexing format - not R's which would start with 1!).


This should work:


if (Which_S2_bands_do_you_want_to_use == 0) {
bands<-c("B((0[2348]_10m)|(((0[567])|(1[12])|(8A))_20m)).jp2$")}

Note that your original code should have worked in QGIS 2.18 and the old R provider!


No comments:

Post a Comment

arcpy - Changing output name when exporting data driven pages to JPG?

Is there a way to save the output JPG, changing the output file name to the page name, instead of page number? I mean changing the script fo...