将列表栅格替换为“ NA”值

时间:2019-08-26 15:12:22

标签: r raster r-raster

我在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)
}

这是我的问题,输出类具有我的所有图像,而不是超过50%的单元格具有值的层

我想将此条件应用于:

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

1 个答案:

答案 0 :(得分:2)

您的示例数据

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]