2

In the r-package terra there is the function terra::extend. To my understanding it just expands the raster with no data values on each side right?

I wanted to do something similar, but using a stars object. My approach kind of looked like this:

  # add.y and add.y are scalars between 0 and 1 to extend the number of cols/rows by e.g. add.x percent

  grid_vals = star[[1]]
  ncol = ncol(grid_vals)
  nrow = nrow(grid_vals)
  new_cols = floor(ncol * add.x); if(!new_cols %% 2 == 0) new_cols = new_cols -1
  new_rows = floor(nrow * add.y); if(!new_rows %% 2 == 0) new_rows = new_rows -1

  # new columns
  for (i in 1:new_cols) {
    if (i %% 2 == 0) {
      grid_vals = cbind(grid_vals, rep(NA, nrow))
    } else{
      grid_vals = cbind(rep(NA, nrow), grid_vals)
    }
  }

  # new rows
  cols = ncol(grid_vals)
  
  for (j in 1:new_rows) {
    if (j %% 2 == 0) {
      grid_vals = rbind(grid_vals, rep(NA, cols))
    } else{
      grid_vals = rbind(rep(NA, cols), grid_vals)
    }
  }

I can create a new matrix with this. However, I do not know how I could assign this to my old stars-object that has a different extent and bounding-box etc...

1 Answer 1

2

With this stars object

library(stars)
f = system.file("ex/elev.tif", package="terra")
s = read_stars(f)

You can do

library(terra)
r = rast(s)
r = extend(r, ext(r)+2)

And then coerce it back to stars

x = st_as_stars(r)
1
  • 1
    Thank you very much!:) I just wondered if I could do the same by only using "stars" objects. But now I did it exactly this way:)
    – Lenn
    Feb 2, 2022 at 10:36

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Not the answer you're looking for? Browse other questions tagged or ask your own question.