R stars collapse an x/y dimension to a single geometry dimension

51 views Asked by At

I have a stars object with 2 'raster-like' grid dimensions (but no projection), of x and y. I also have a polygon sf file that contains a field that contains a combination of xy element ids that the polygons correspond to (but will be a subset of them!). I want to reshape the star to remove the xy dimensions and replace with the single geometry dimension. Essentially the equivalent of doing a table join between the data in the star with the xy dimensions.

Here is a reprex:

# create a star
x = seq(1,5,1)
y = seq(1,8,1)
z = seq(1,3,1)
t = seq(1,4,1)

d <- st_dimensions(x=x, y=y,z=z,t=t)

values <- runif(length(x) * length(y) * length(z) * length(t))
data = array(values, dim = c(length(x),
                             length(y),
                             length(z),
                             length(t)))

star <- st_as_stars(data = data,  dimensions = d)
star

# create an arbitrary geometry of a subset of the number of x and y
nc = sf::read_sf(system.file("gpkg/nc.gpkg", package = "sf"), "nc.gpkg") |>
  head(0.5 * length(x) * length(y)) |>  # the number of polygons < total number of x * y grid elements
  select(geom) |>
  # add an x-y ID, these are what should be 'joined' with the star xy
   mutate(x = c(rep(1,4), rep(2,4), rep(3,4), rep(4,4), rep(5,4)),
         y = rep(c(1,3,5,8),5),
         label = paste0(x,"-",y))

I basically need to extract the elements of the star in the nc$label column and make a new star with the geometry of nc applied.

I tried doing something like:

st.g <- star |> filter(x %in% c(1.5,2.5,3.5,4.5,5.5),
                       y %in% c(1.5,3.5,5.5,8.5)) 

(nc.geom <- st_set_dimensions(st.g, 1, st_geometry(nc)))

but I get an error because the dimensions don't match.

ANy idea how to reduce the xy dimension of the star by matching to the xy data stored in the geometry file?

0

There are 0 answers