Warning: file_get_contents(/data/phpspider/zhask/data//catemap/4/r/79.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
R焦点(光栅)-条件过滤器(仅当窗口中心为值1时运行)_R_Filtering_Raster - Fatal编程技术网

R焦点(光栅)-条件过滤器(仅当窗口中心为值1时运行)

R焦点(光栅)-条件过滤器(仅当窗口中心为值1时运行),r,filtering,raster,R,Filtering,Raster,我想过滤一个大的光栅,但仅当窗口的中心单元格是一个特定值时才运行过滤器。基本上,我希望从图像(像素为0或1)中删除一些斑点(误报),但仅在窗口中心为1时运行过滤器 # create some raster data library(raster) r <- raster(ncols=12, nrows=12) set.seed(0) r[] <- round(runif(ncell(r))*0.7 ) plot(r) #创建一些光栅数据 图书馆(光栅) r可以通过将函数传递给foc

我想过滤一个大的光栅,但仅当窗口的中心单元格是一个特定值时才运行过滤器。基本上,我希望从图像(像素为0或1)中删除一些斑点(误报),但仅在窗口中心为1时运行过滤器

# create some raster data
library(raster)
r <- raster(ncols=12, nrows=12)
set.seed(0)
r[] <- round(runif(ncell(r))*0.7 )
plot(r)
#创建一些光栅数据
图书馆(光栅)

r可以通过将函数传递给
focal
fun
参数。 像这样传递的函数应该对数值向量进行操作。如果使用5x5权重矩阵,则中心单元格将是该数值向量的第13个元素。可以使用此信息检查中心单元格的开头是否为0,并有条件地返回值

r[sample(1:ncell(r), 30)] <- NA # add NA values to example raster

gol_fun <- function(x) {

  # more general definition of center cell for weight matrices with odd side size
  center <- x[ceiling(length(x)/2)]

  if (center==0 | is.na(center)) { # handle NA values
    return(center)
  } 

  ncells <- sum(x, na.rm=TRUE)

  if (ncells<5) { #  window with with less than 5 cells die
    return(0)
  } else if (ncells >= 5) { # window with 5 or more cells live
    return(1)
  }
}




gameOfLife <- function(x) {
  f <- focal(x, w=w, fun=gol_fun, pad=TRUE, padValue=0)
}


plot(r)
plot(gameOfLife(r))

r[示例(1:ncell(r),30)]非常感谢joberlin!最后一个问题,如果你愿意的话。我的光栅显然比示例场景要复杂一些,并且具有破坏该功能的NAs。我一直在自己尝试(未成功)调整您的代码以通过NAs工作,但遇到了麻烦。r[12,8]注释超时我尝试在初始if子句之后添加一个额外的if-else以跳过if-NA。Def感觉厚b/c我无法修复这一点…我已编辑了我的答案,以便该函数现在包括处理NA值,并将NA值添加到示例光栅中。
r[sample(1:ncell(r), 30)] <- NA # add NA values to example raster

gol_fun <- function(x) {

  # more general definition of center cell for weight matrices with odd side size
  center <- x[ceiling(length(x)/2)]

  if (center==0 | is.na(center)) { # handle NA values
    return(center)
  } 

  ncells <- sum(x, na.rm=TRUE)

  if (ncells<5) { #  window with with less than 5 cells die
    return(0)
  } else if (ncells >= 5) { # window with 5 or more cells live
    return(1)
  }
}




gameOfLife <- function(x) {
  f <- focal(x, w=w, fun=gol_fun, pad=TRUE, padValue=0)
}


plot(r)
plot(gameOfLife(r))