Search code examples
rplotterra

Why can I not add a date as a title in terra::rast?


I'm slowly transitioning over to terra::rast from raster, and I noticed I am not able to add a date to my title. I have figured out a workaround (reassign to character), but I'm wondering why this doesn't work when it worked in raster? The error message is not too informative.

Here's an example:

dates <- seq(as.Date("2015-06-24"), as.Date("2016-01-01"), by=1)
test <- terra::rast(nrows=100, ncols=100, xmin=0, xmax=100, ymin=0, ymax=100,
                      crs="+proj=utm +zone=46 +datum=WGS84 +units=m +no_defs", 
                      resolution=10)
values(test) <- runif(10000)
plot(test, col=viridis::plasma(11), main=dates[4], breaks = c(seq(0, 1, by=0.1)))

Error in if (main != "") { : missing value where TRUE/FALSE needed

This code works when doing the following:

plot(test, col=viridis::plasma(11), main=as.character(dates[4]), 
     breaks = c(seq(0, 1, by=0.1)))

Thoughts?


Solution

  • The error is exactly the problem. At some point in the code, the main argument is tested to see if it is the empty string "" with the line if(main != ""). But comparing a Date class object to an empty string gives a missing value NA result:

    Sys.Date() == ""
    # [1] NA
    

    And an if() statement throws an error if you give it NA:

    if(NA){}
    # Error in if (NA) { : missing value where TRUE/FALSE needed
    

    So the code is assuming main is a character class object. This is documented, the ?terra::plot description of the main argument is:

    character. Main plot titles (one for each layer to be plotted)

    Luckily (see comments), it seems like support for dates was added recently, so you can install the new version from Github!