Search code examples
rgeospatialrgee

adding properties to each feature of Feature Collection in rgee


I want to add a property to each element of a Feature Collection using rgee. This feature collection I have is just a list of polygons, and I want to add an ID (which is different) for each of these geometries. So far, I have:

library(rgee)
library(dplyr)
library(readr)

download data here

#Read polygons 
collection <- read_rds("polygons.rds")
    # convert collection to feature collection using sf_as_ee 
featcol <- sf_as_ee(collection$geometry)

So for each element of this collection, I want to add a property called site_no (site number)

site_no <- collection$site_no

If I do:

withMoreProperties = featcol$map(function(f) {
  # Set a property.
  f$set("site_no", site_no)
})

It doesn't work, instead of adding one site number to each element, it adds all site numbers to all the sites.

Any suggestions on how to fix this? maybe using a loop? or an ee$List?


Solution

  • library(rgee)
    library(dplyr)
    library(readr)
    
    collection <- read_rds("polygons.rds")
    # convert collection to feature collection using sf_as_ee
    
    # Simple solution
    collection_with_prop <- collection[c("site_no", "geometry")] %>%
      st_as_sf() %>% 
      sf_as_ee()
    ee_as_sf(collection_with_prop)
    
    # Add properties in the server-side (using ee$List$zip)
    geom_with_prop <- sf_as_ee(collection$geometry)
    prop_to_add <- collection$site_no %>% ee$List()
    collection_with_prop <- geom_with_prop %>% 
      ee$FeatureCollection$toList(nrow(collection)) %>% 
      ee$List$zip(prop_to_add) %>% # Pairs the elements of two lists to create a list of two-element lists
      ee$List$map(
        ee_utils_pyfunc(function(l){
          lpair <- ee$List(l)
          ee$Feature(lpair$get(0))$set('site_no', lpair$get(1))    
        })    
      ) %>% 
      ee$FeatureCollection()
    ee_as_sf(collection_with_prop)