How to transform a sf table to a stars cube with stars::st_as_stars function?

70 views Asked by At

I want to transform a sf data.frame into a stars cube, and choose the dimensions. But I don't succeed in using the function stars::st_as_stars properly and get what I want. Why do I want to transform it ? Avoid duplications of spatial polygons in my data (see sf_dta below).

In this example, I want :

  • the following dimensions : geometry, weekdays and hours.
  • the following attributes : population.

Help please :)

library(sf)
library(stars)
library(dplyr)

# Create example spatial data --------------------------------------------------

spatial_dim <- st_sf(
  ID = 1:3, 
  geometry = list(
    st_polygon(list(
      cbind(c(0, 1, 1, 0, 0), c(0, 0, 1, 1, 0))
    )),
    st_polygon(list(
      cbind(c(1, 2, 2, 1, 1), c(0, 0, 1, 1, 0))
    )),
    st_polygon(list(
      cbind(c(2, 3, 3, 2, 2), c(0, 0, 1, 1, 0))
    ))
  )
)

weekdays_dim <- data.frame(weekdays = c("Monday", "Tuesday", "Wednesday", "Thursday", "Friday", "Saturday", "Sunday"))
hours_dim <- data.frame(hours = c("8am", "11am", "4pm", "11pm"))
sf_dta <- spatial_dim |> 
  cross_join(weekdays_dim)|> 
  cross_join(hours_dim) |> 
  mutate(population = rnorm(n(), mean = 1000, sd = 200)) |> 
  select(everything(), geometry)


# Try to transform as a stars object with dimensions : geometry, weekdays, hours -----

st_as_stars(sf_dta, name = attr(dta, "sf_column"), dims = c('jour','geometry'))

Unfortunately, this code returns an error :

Error in st_as_stars.sf(sf_dta, name = attr(dta, "sf_column"), dims = c("jour", : ... arguments ignored

1

There are 1 answers

1
Edzer Pebesma On BEST ANSWER

This seems to work:

st_as_stars(as.data.frame(sf_dta), dims = c("weekdays", "hours", "geometry")) |>
   st_set_dimensions(xy = NA)

but there definitely is some room for improvement to make this somewhat more intuitive.