2016-03-02 82 views
2

我有三个SpatialPointsDataFrame实际上只有一个点的对象。我的目的是为包含该点的每个区域创建一个栅格,以便除点之外的所有单元都为“NA”,因此我可以使用包raster中的distance()函数生成栅格其中z值是到z不是“NA”的唯一单元格的距离。R中的光栅化函数的问题

我的代码工作,而不与第一三个对象的问题,但似乎其他两个以下错误:

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) 

编辑:我已经尝试过了转向一个SpatialGridDataF rame和我可以绘制它,但我的观点并不在光栅的范围内,即情节是空的。代码:

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平方公里,这是我以前使用的行数和列数。有任何想法吗?

回答

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,所以我认为这是你想要的。