Search code examples
rpackagegoogle-colaboratoryrasterterra

How to install terra / raster packages in R Google Colab?


I'm trying to install terra package in R Google Colab, but it is not working.

It returns:

“installation of package ‘terra’ had non-zero exit status”

I tried the solutions found in here and here, i.e., trying to install dependencies like GDAL via system("apt install libudunits2-dev libgdal-dev libgeos-dev libproj-dev" ) but it does not work.

Is it possible to run terra in Google Colab (or even raster) packages?


Solution

  • I was able to install terra on Google Colab using the code below. It did take about 5-10 minutes for the library to install.

    1. In Google Colab, select "Runtime", "Change runtime type" and select "R" under "Runtime type".

    2. Install terra per the instructions on the module's GitHub page:

    install.packages("Rcpp")
    
    Sys.setenv("R_REMOTES_NO_ERRORS_FROM_WARNINGS" = "true")
    remotes::install_github("rspatial/terra")
    
    #read in packages
    library(terra)
    
    1. Test that the module is imported and working, the code block below is from the rspatial.org site:
    ## terra 1.7.36
    # create an empty SpatRaster
    r <- rast(ncol=10, nrow=10)
    # assign values to cells
    values(r) <- 1:ncell(r)
    s <- r + 10
    s <- sqrt(s)
    s <- s * r + 5
    values(r) <- runif(ncell(r))
    r <- round(r)
    r <- r == 1
    r
    

    Output is below:

    class       : SpatRaster 
    dimensions  : 10, 10, 1  (nrow, ncol, nlyr)
    resolution  : 36, 18  (x, y)
    extent      : -180, 180, -90, 90  (xmin, xmax, ymin, ymax)
    coord. ref. : lon/lat WGS 84 
    source(s)   : memory
    name        : lyr.1 
    min value   : FALSE 
    max value   :  TRUE 
    

    Additional code block:

    x <- rast(ncol=36, nrow=18, xmin=-1000, xmax=1000, ymin=-100, ymax=900)
    res(x)
    ## [1] 55.55556 55.55556
    
    res(x) <- 100
    res(x)
    

    Output:

    55.555555555555655.5555555555556
    100100