我想使用extract()
来计算给定栅格(ras
)中的某些坐标的缓冲区内像素值为“ 1”的百分比。
在我的示例中:
#Packages
library(raster)
# Create a raster
ras <- raster(ncol=1000, nrow=1000)
set.seed(0)
values(ras) <- runif(ncell(ras))
values(ras)[values(ras) > 0.5] = 1
values(ras)[values(ras) < 0.5] = NA
ras
#class : RasterLayer
#dimensions : 1000, 1000, 1e+06 (nrow, ncol, ncell)
#resolution : 0.36, 0.18 (x, y)
#extent : -180, 180, -90, 90 (xmin, xmax, ymin, ymax)
#crs : +proj=longlat +datum=WGS84 +no_defs
#source : memory
#names : layer
#values : 1, 1 (min, max)
# Create some 30 coordinates
pts<-sampleRandom(ras, size=30, xy=TRUE)
pts.df<-as.data.frame(pts)
pts.df$area<-rnorm(30, mean=10)
head(pts.df)
# x y layer area
#1 -109.26 -43.65 1 10.349010
#2 93.42 -87.21 1 9.861920
#3 57.06 86.85 1 8.642071
#4 -109.98 -45.63 1 10.376485
#5 -92.34 37.89 1 10.375138
#6 19.62 21.51 1 8.963949
#Representation
plot(ras)
points(cbind(pts.df$x,pts.df$y))
#Function for extract percentual 1s
perc1<- function(x,...) {
leng1<-length(values(x) ==1) # length of 1s pixels
lengtotal<-length(x) # total length of pixels inside buffer
perc<-(leng1/lengtotal)*100
return(perc)
}
# Extract circular, 100000 units buffer
cent_max <- raster::extract(ras, # raster layer
cbind(pts.df$x,pts.df$y), # SPDF with centroids for buffer
buffer = 100000, # buffer size
fun=perc1, # what to value to extract
df=TRUE)
在这里,我需要有关编程问题的帮助,因为perc1
函数不起作用。我想使用extract()
创建一个新列(percentual_1s),该列占像素的百分比
值为“ 1”。我需要一些方向来计算像素的length()
,其中像素“ 1”除以每个100000单位缓冲区* 100中像素的总数(“ 1”的值和NA)。我的理想
输出是:
# x y layer area percentual_1s
#1 -109.26 -43.65 1 10.349010 23.15
#2 93.42 -87.21 1 9.861920 45.18
#3 57.06 86.85 1 8.642071 74.32
#4 -109.98 -45.63 1 10.376485 11.56
#5 -92.34 37.89 1 10.375138 56.89
#6 19.62 21.51 1 8.963949 88.15
请问有什么想法吗?
答案 0 :(得分:0)
使您的函数适合提取,如下所示:
percentual_1s<- function(x,...) {
leng1<-length(which(x==1))
lengtotal<-length(x)
perc<-(leng1/lengtotal)*100
return(perc)
}
并在提取调用中添加“ na.rm = FALSE”:
cent_max <- extract(ras, pts[,1:2], buffer = 1000000, fun=percentual_1s, df=TRUE, na.rm = FALSE)
那给了我
head(cent_max)
ID layer
1 1 49.81865
2 2 50.27545
3 3 50.03113
4 4 50.29819
5 5 50.39391
6 6 48.89556
https://stat.ethz.ch/pipermail/r-sig-geo/2020-September/028437.html
中的解决方案