替换 R 中每个光栅砖带中的特定值 [英] Replace specific value in each band of raster brick in R

查看:52
本文介绍了替换 R 中每个光栅砖带中的特定值的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我使用 brick() 将一个多波段(20 层)光栅作为 RasterBrick 加载到 R 中.我的计划是使用此线程中提出的方法将每个波段从 0 标准化为 1:https://stats.stackexchange.com/questions/70801/how-to-normalize-data-to-0-1-range

I have a multi-band (20 layers) raster loaded into R as a RasterBrick using brick(). My plan is to normalize each band from 0 to 1 using the approach that was proposed in this thread: https://stats.stackexchange.com/questions/70801/how-to-normalize-data-to-0-1-range

这里有一些示例代码来可视化我的问题:

Here some sample code to visualize my problem:

for(j in 1:nlayers(tif)){
  min <- cellStats(tif[[j]],'min')
  max <- cellStats(tif[[j]],'max')
  for(i in 1:ncell(tif)){
    tif[i][j] <- (tif[i][j]-min)/(max-min)    
  }
}

tif"包含光栅砖.j"是tif"的当前层,而i"是层[[i]]的当前单元格.我认为其余的很简单.现在的问题是,替换特定波段中的单个值需要数小时才能完成.为什么要花这么长时间才完成?

"tif" contains the raster brick. "j" is the current layer of "tif", while "i" is the current cell of layer[[i]]. I think the rest is pretty straight forward. The problem now is that it takes hours without finishing to replace a single value in a specific band. Why is it taking so long without finishing?

干杯,凯

推荐答案

您的方法非常低效,因为您一次只循环遍历每个单元格一次.对于较大的栅格,这需要很长时间.

Your approach is very inefficient because you are looping over each cell individually once at a time. This takes forever for larger rasters.

您可以使用 Geo-sp 的答案中的方法(如果您的栅格较大,我也不推荐这种方法)或使用 clusterR 函数:

You can either use the approach from Geo-sp's answer (which I also wouldn't recommend if your raster is larger) or use the clusterR function:

norm <- function(x){(x-min)/(max-min)}

for(j in 1:nlayers(tif)){

  cat(paste("Currently processing layer:", j,"/",nlayers(tif), "\n"))

  min <- cellStats(tif[[j]],'min')
  max <- cellStats(tif[[j]],'max')

  #initialize cluster
  #number of cores to use for clusterR function (max recommended: ncores - 1)
  beginCluster(3)

  #normalize
  tif[[j]] <- clusterR(tif[[j]], calc, args=list(fun=norm), export=c('min',"max"))

  #end cluster
  endCluster()
}

这篇关于替换 R 中每个光栅砖带中的特定值的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆