0

我有下面的空间数据集。它由空间中的点组成,这些点构成了每个 ID(例如个体动物)的轨迹。

library(tidyverse)
library(sf)

id <- c("2017_844_1", "2017_844_1", "2017_844_1", "2017_844_1", "2017_844_2",
        "2017_844_2", "2017_844_2", "2017_844_2", "2017_844_3", "2017_844_3",
        "2017_844_3", "2017_844_3")
lat <- c(-30.6456, -29.5648, -27.6667, -31.5587, -30.6934, -29.3147, -23.0538, 
         -26.5877, -26.6923, -23.40865, -23.1143, -23.28331)
long <- c(-50.4879, -49.8715, -51.8716, -50.4456, -50.9842, -51.9787, -41.2343, 
          -40.2859, -40.19599, -41.64302, -41.58042, -41.55057)
speed_km <- c(3.4565, 4.9799, 3.2546, 5.4689, 8.5454, 7.4856, 5.8798, 3.6544,
               6.8452, 5.2345, 3.4565, 4.8845)
df <- tibble(id, lat, long, speed_km)

#converting ​to sf
df_sf <- df %>% 
 ​sf::st_as_sf(coords = c("long", "lat"), crs = 4326)

library(raster)

#creating grid
xy <- sf::st_coordinates(df_sf)

grid = sf::st_make_grid(sf::st_bbox(df_sf),
                       ​cellsize = .1, square = FALSE) %>%
 ​sf::st_as_sf() %>%
 ​dplyr::mutate(cell = 1:nrow(.)) 

r <- raster::raster(grid, res=0.1)

但是,我需要它是一个循环,为每个 ID 执行此过程,以便为每个 ID 生成一个栅格对象,其中包含每个网格单元的平均速度值。我通过这段代码得到了它,但值都是0:

rs <- stack(r)   

for(i in unique(df_sf$id)) {
  rs <- addLayer(rs, rasterize(x = df_sf[df_sf$id == i,], y = r, 
                               field = 1, 
                               fun=function(x,...)mean(df_sf$speed_km), 
                               background = 0))
}

names(rs) <- unique(df_sf$id) 
df_sf2 <- as.data.frame(rs, xy=T, centroids=T) %>%
  mutate(cell = 1:nrow(.)) 

在此先感谢您的帮助

4

0 回答 0