r-spatial / rgee

Google Earth Engine for R
https://r-spatial.github.io/rgee/
Other
677 stars 146 forks source link

Unable to select feature from featureCollection by attribute table filter in a loop #301

Closed rokoeh closed 1 year ago

rokoeh commented 1 year ago

rgee version: rgee 1.1.4 R version: 4.2.1 Operating System: Win 10

What I want to do is download sentinel2 data for every polygon(feature) from a shapefile (featureCollection) in a loop. Every iteration of the loop downloads the data of a different polygon to my computer.

I am able to select the feature directly from my script or command line with : newShp<- shp$filter('atribute_column_name == "selection_critirea"')

I cant make it work in a loop. Maybe I'm not pasting the correct command to make it work? Here is what I am trying:

shid<-shapefile("D:/temp/rgee_example/feat1.shp")

ids<-shid$text1

require(rgee) require(mapview)

ee_Initialize(drive = TRUE)

shp<-ee$FeatureCollection("users/*****/feat1")

sentinel2 <- ee$ImageCollection$Dataset$COPERNICUS_S2$ filterDate("2021-08-01","2021-08-30")$ filterBounds(shp)

sentBands<-sentinel2$toBands()

for(k in 1:length(ids)){

nshp<-shp$filter(paste0("'text1 == " ,'"', ids[k] ,'"', "'")) # how can I run this in every iteration of the loop?

sentBands<-sentBands$clip(nshp)

info<-sentBands$getInfo()

b2Sele<-NULL

for(i in 1:length(info$bands)){

imId<-info$bands[[i]]$id

if(length(grep("_B2",imId))==1)b2Sele[length(b2Sele)+1]<-imId

}

sentB2 <- sentBands$select(c(b2Sele))

ee_raster <- ee_as_raster(
  image = sentB2,
  region = nshp$geometry(),
  dsn = paste0("D:/gee/sentinel2/date_stack/sentinel2_B2_",ids[k],".tif"),
  via = "drive"
)

}

The error :

Error in py_call_impl(callable, dots$args, dots$keywords) : ee.ee_exception.EEException: Collection.filter: Expression parse error at character 0: ''text1 == "id1"'' ^.

But if I run it from command line it works fine (in this case I directly type the id that i want to use in the selection criteria):

shid<-shapefile("D:/temp/rgee_example/feat1.shp")

ids<-shid$text1

require(rgee) require(mapview)

ee_Initialize(drive = TRUE)

shp<-ee$FeatureCollection("users/****/feat1")

sentinel2 <- ee$ImageCollection$Dataset$COPERNICUS_S2$ filterDate("2021-08-01","2021-08-30")$ filterBounds(shp)

sentBands<-sentinel2$toBands()

nshp<-shp$filter('text1 == "id1"') #cant make this work in a loop

k=1

sentBands<-sentBands$clip(nshp)

info<-sentBands$getInfo()

b2Sele<-NULL

for(i in 1:length(info$bands)){

imId<-info$bands[[i]]$id

if(length(grep("_B2",imId))==1)b2Sele[length(b2Sele)+1]<-imId

}

sentB2 <- sentBands$select(c(b2Sele))

ee_raster <- ee_as_raster(
  image = sentB2,
  region = nshp$geometry(),
  dsn = paste0("D:/gee/sentinel2/date_stack/sentinel2_B2_",ids[k],".tif"),
  via = "drive"
)

output:

Shapefile used in this test: feat1.zip

With best regards