r-spatial / rgee

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

The example on conditional operators does not work #323

Closed fBedecarrats closed 1 year ago

fBedecarrats commented 1 year ago

Hello, I think that the exemple provided on conditional operators on the rgee book does not work. It is written with nl2012.expression(), which can't be right (and doesn't work). I tried with nl2012$expression() but something is wrong with the syntax.

nl2012 <- ee$Image("NOAA/DMSP-OLS/NIGHTTIME_LIGHTS/F182012")
zonesExp <- nl2012$expression(
  "(b('stable_lights') > 62) ? 3" +
    ": (b('stable_lights') > 55) ? 2" +
    ": (b('stable_lights') > 30) ? 1" +
    ": 0"
)
ee_print(zonesExp)
# Error in "(b('stable_lights') > 62) ? 3" + ": (b('stable_lights') > 55) ? 2" : 
#   non-numeric argument to binary operator
csaybar commented 1 year ago

Sorry for the late reply. Here is a reproducible example. Hint: In R the plus operator does not concatenate strings by default.

library(rgee)

ee_Initialize()

`+` <- function(x, y) {
  if (is.character(x) && is.character(y)) {
    return(paste0(x, y))
  }
  UseMethod("+")
}

nl2012 <- ee$Image("NOAA/DMSP-OLS/NIGHTTIME_LIGHTS/F182012")

zonesExp <- nl2012$expression(
  expression = "(b('stable_lights') > 62) ? 3" +
    ": (b('stable_lights') > 55) ? 2" +
    ": (b('stable_lights') > 30) ? 1" +
    ": 0"
)
zonesExp$getInfo()
fBedecarrats commented 1 year ago

Nice one! Maybe it would be useful to update the example on the regee guidebook ? https://r-earthengine.com/rgeebook/image.html?q=conditional%20#conditional-operators