如何使用stars::st_as_stars函数将sf表转换为stars立方体?

wkyowqbh  于 11个月前  发布在  其他
关注(0)|答案(1)|浏览(93)

我想把一个sf data.frame转换成一个stars立方体,并选择维度。但是我没有成功地正确使用函数stars::st_as_stars并得到我想要的。为什么我想转换它?避免在我的数据中重复空间多边形(参见下面的sf_dta)。
在这个例子中,我想要:

  • 以下维度:几何形状、工作日和小时。
  • 以下属性:人口。

请帮帮忙:)

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'))

字符串
不幸的是,这段代码返回一个错误:
Error in st_as_stars.sf(sf_dta, name = attr(dta, "sf_column"), dims = c("jour", : ... arguments ignored

syqv5f0l

syqv5f0l1#

这似乎起作用:

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

字符串
但肯定还有一些改进的空间,使其更加直观。

相关问题