rsearchfile-listing

List files with multiple conditions part2


I have the following rasters and would like to import them in R. My files are now called:

B02_10m.jp2
B03_10m.jp2
B04_10m.jp2
B08_10m.jp2

B05_20m.jp2
B06_20m.jp2
B07_20m.jp2
B8A_20m.jp2
B11_20m.jp2
B12_20m.jp2

They are located in different sub-folders. That's way I am using recursive=TRUE

I have trying with the following options to combine the conditions but it's not working.

 S2 <- "my/path"
S2 <- list.files(S2, recursive = TRUE, full.names = TRUE, pattern =  "B0[2348]_10m.jp2$ | B(0[567]_20m)|(1[12]_20m)|(8A_20m).jp2$")

S2 <- "my/path"
S2 <- list.files(S2, recursive = TRUE, full.names = TRUE, pattern =  "B0[2348]_10m | B(0[567]_20m)|(1[12]_20m)|(8A_20m).jp2$")

Solution

  • For other users and based on @docendo discimus answer, here is the idea to combine different conditions when listing files as in my case. My conditions are based on the numbers that are following the letter B so:

    pattern="B( here we need to write the conditions).jp2$
    

    First, we will set the condition to import the files B02_10m, B03_10m, B04_10m, B08_10m

    patter="B(FIRST CONDITION OR SECOND CONDITION).jp2$
    pattern="B((0[2348]_10m)|SECOND CONDITION).jp2$
    

    Second, we will import the files B05_20m, B06_20m, B07_20m, B8A_20m, B11_20m, B12_20m. In this case, we have to combine several sub-conditions because the pattern changes from e.g.: 02 to 11, 12 and 8A

    First we write the code for 5, 6 and 7

    pattern="B((0[2348]_10m)|((0[567])_20m)).jp2$
    

    Then we add the code for bands 11 and 12

    pattern="B((0[2348]_10m)|((0[567])|(1[12])_20m)).jp2$
    

    Then, the code for 8A

    pattern="B((0[2348]_10m)|(((0[567])|(1[12])|(8A))_20m)).jp2$
    

    Hope it's clear