用 'NA' 值替换列表栅格

Replace in a list rasters with 'NA' values

我在 GeoTIFF 文件中有一个栅格文件列表,如果一个文件的 NA 值超过 50%,我想删除每个文件。

我想从我的新列表 (f2) 中删除它。在我的代码中:

library(raster)

# example data
r <- raster(ncol=10, nrow=10)

set.seed(0)
# 10 layers
s <- stack(lapply(1:10, function(i) setValues(r, runif(ncell(r)))))
# set about half the values to NA
s[s < .5] <- NA

#Create GeoTIFF for each layer
sl<-1:10
for (i in 1:length(sl)){
writeRaster(s[[i]],filename=paste(sl[i],sep=""),
                  format="GTiff",datatype="FLT4S",overwrite=TRUE)
}

#Take images in batch
f <- list.files(getwd(), pattern = ".tif") 
ras <- lapply(f,raster)

#Remove from my list when I have more than 50% of cells that are NA
class <- vector()
for (j in 1:length(ras)){
i <- cellStats(is.na(ras[[j]]), sum) # count the NA values in each layer
i <- i/ncell(ras[[j]]) # fraction that is NA
ss <- ras[[j]][[which(i>.5)]] # Select the layers that more than half the cells with values
class<-c(class,ss)
}

这里,我遇到了问题,输出 class 包含我的所有图像,而不是超过 50% 的单元格具有值的层

我想将此条件应用于:

#Remove target images
f2 <- list.files(getwd(), pattern = ".tif") 
f2<- f[f!=class]
ras2 <- lapply(f2,raster)

您的示例数据

library(raster)
r <- raster(ncol=10, nrow=10)
set.seed(0)
s <- stack(lapply(1:10, function(i) setValues(r, runif(ncell(r)))))
s[s < .5] <- NA

# I skip the file writing bit. But from these files I would make a RasterStack again
#f <- list.files(getwd(), pattern = ".tif") 
#ras <- stack(f)

计算NA的细胞数并除以细胞数

f <- freq(s, value=NA) / ncell(s)
# equivalent to cellStats(is.na(s), "mean")
i <- which(f <= 0.5)
i
#layer.2 layer.6 layer.7 
#      2       6       7 

使用这些索引对 RasterStack 进行子集化

ss <- s[[i]]

如果你不能从你的真实数据中创建一个 RasterStack(可能栅格没有对齐),你可以使用一个列表和一个像这样的循环

ras <- as.list(s)

result <- rep(NA, length(ras))
for (i in 1:length(ras)){
    result[i] <- freq(ras[[i]], value=NA) / ncell(ras[[i]])
}
# equivalent to
# result <- sapply(1:length(ras), function(i) freq(ras[[i]], value=NA) / ncell(ras[[i]]))

j <- result < 0.5
sras <- ras[j]