R 中光栅化函数的问题

Problems with rasterize function in R

我有三个 SpatialPointsDataFrame 个对象,实际上每个对象只有一个点。我的目的是为它们中的每一个制作一个栅格,其范围包括点,这样除了点之外的所有单元格都是 "NA",这样我就可以在中使用 distance() 函数包 raster 以生成一个栅格层,其中 z 值是到唯一一个 z 不是 "NA" 的像元的距离。

我的代码对三个对象中的第一个没有问题,但其他两个出现以下错误:

    error in seq.default(zrng[1], zrng[2], length.out = cuts + 2) : 
    'from' cannot be NA, NaN or infinite
    In addition: Warning messages:
    1: In asMethod(object) :
      complete map seems to be NA's -- no selection was made
    2: In min(x) : no non-missing arguments to min; returning Inf
    3: In max(x) : no non-missing arguments to max; returning -Inf

我已经双重和三次检查我的点是否包含在栅格范围内,但我确实无法查明问题所在

这是我的代码:

library(raster)

TIM <- data.frame()
TIM[1,1] <- -13.8309
TIM[1,2] <- 28.9942

VEN <- data.frame()
VEN[1,1] <- -15.7886
VEN[1,2] <- 27.8444

MCL <- data.frame()
MCL[1,1] <- -13.5325
MCL[1,2] <- 29.2914


coordinates(TIM) <- ~V1+V2
coordinates(VEN) <- ~V1+V2
coordinates(MCL) <- ~V1+V2

bb2 <- matrix(c(-20, -9.5, 20.5, 31.5), nrow = 2, ncol = 2, byrow = T)
bb2 <- extent(bb2)

r <- raster(nrows = 1217, ncols = 1047)
r <- setExtent(r, bb2, keepres=F)

rMCL <- rasterize(MCL, r)
spplot(rMCL)

#so far so good, but from now on it doesn't work

rVEN <- rasterize(VEN, r)
spplot(rVEN)


rTIM <- rasterize(TIM, r)
spplot(rTIM)

编辑:我尝试将其转换为 SpatialGridDataFrame 并对其进行绘制,但我的观点不在栅格范围内,即该图为空。代码:

rr <- as(rTIM, "SpatialGridDataFrame")
spplot(rr)
#this produces an empty plot

我也试过在没有预先确定的列数和行数的光栅中绘制它,并且它有效:

r <- raster()
r <- setExtent(r, bb2, keepres=F)
rTIM <- rasterize(TIM, r)
spplot(rTIM)
# this produces a raster containing my point

问题是,我真的需要设置绘图的分辨率,使栅格的每个像元代表大约 1 平方公里,这是我之前使用的行数和列数得到的。有什么想法吗?

我可以通过将所有三组坐标添加到同一数据帧然后在创建栅格时使用计数函数来使其工作:

library(raster)

# Add all 3 sets of coordinates to the same dataframe

df <- data.frame()
df[1,1] <- -13.8309
df[1,2] <- 28.9942
df[2,1] <- -15.7886
df[2,2] <- 27.8444
df[3,1] <- -13.5325
df[3,2] <- 29.2914

# Create new column in dataframe (we will use this for the count function)

df$x <- c(1,1,1)

# Convert to spatial points dataframe

df.sp <- df
coordinates(df.sp) <- ~ V1+V2

# Make raster

bb2 <- matrix(c(-20, -9.5, 20.5, 31.5), nrow = 2, ncol = 2, byrow = T)
bb2 <- extent(bb2)

r <- raster(nrows = 1217, ncols = 1047)
r <- setExtent(r, bb2, keepres=F)

# Rasterise using the count function

raster <- rasterize(df.sp, r, field= "x", fun="count")

# The table shows there are 3 cells with a value of 1 so it seems to have worked

table(values(raster))

1 
3 

spplot(raster)

raster

class       : RasterLayer 
dimensions  : 1217, 1047, 1274199  (nrow, ncol, ncell)
resolution  : 0.01002865, 0.00903862  (x, y)
extent      : -20, -9.5, 20.5, 31.5  (xmin, xmax, ymin, ymax)
coord. ref. : +proj=longlat +datum=WGS84 +ellps=WGS84 +towgs84=0,0,0 
data source : in memory
names       : layer 
values      : 1, 1  (min, max)

这个图对我来说没有多大意义,但我认为那是因为你的栅格中有很多像元,所以你看不到任何东西。栅格中的值肯定是 3 个值为 1 的单元格,其余所有单元格都是 NA,所以我认为这就是你想要的。