我有三个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平方km,这就是我之前使用的行数和列数。有什么想法吗?
答案 0 :(得分:0)
我可以通过将所有三组坐标添加到同一数据帧然后在创建栅格时使用count函数来实现它:
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,所以我认为这就是你想要的。