不创建 SpatialGridDataFrame 对象的函数

Function that don't create SpatialGridDataFrame object

我尝试创建一个函数来转换辐射度中卫星图像的数字数字,但我不知道为什么我的最终对象是数字而不是 SpatialGridDataFrame 对象,如果我在我的函数中指定 class (结果)== "SpatialGridDataFrame"。 我的代码是:

套餐

require(raster)
require(sp)

RasterLayer 模拟

r <- raster(nrows=10, ncols=10)
r <- setValues(r, 1:ncell(r))
plot(r)

band2<- as(r, 'SpatialGridDataFrame')  ### convert in SpatialGridDataFrame

DN 到 radiance 的函数

radconvL<-function(x, band = 2)
{
     Lmax <- switch(as.character(band), 
                    "2" = 120.64,
                    "3" = 151.31,
                    "4" = 157.57,
                    "5" = 69.03,
                    NA)

     if (is.na(Lmax)) stop("invalid band")

     Lmin = 0
     Qmax = 127
     x <- as.vector(as.matrix(x))
     results <- x

     x <- Lmin + ((Lmax-Lmin)*x)/Qmax
     if (class(results) == "SpatialGridDataFrame")
         results@data[, 1] <- x
     else if (is.data.frame(x))
         results <- data.frame(matrix(x, nrow = nrow(results),
             ncol = ncol(results)))
     else results <- x
     print(paste(band, Lmax))
     print(results)
     results
}
--

尝试函数

teste2<-radconvL(band2, band = 2)
str(test2)## Numeric!!!! Why???

有人可以帮我吗?

谢谢,

亚历山大

我将向您展示如何完成这项工作:

radconvL <- function(x, band = 2) {
     Lmax <- switch(band, 
                    "2" = 120.64,
                    "3" = 151.31,
                    "4" = 157.57,
                    "5" = 69.03,
                    NA)

     if (is.na(Lmax)) stop("invalid band")
     Lmin = 0
     Qmax = 127
     Lmin + ((Lmax-Lmin)*x)/Qmax
}

library(raster)
b <- brick(system.file("external/rlogo.grd", package="raster"))
test <- radconvL(b[[2]], band = 2)

testRasterLayer,但如果您需要 SpatialGridDataFrame(为什么?),请使用:

sptest <- as(test, 'SpatialGridDataFrame')

这不是您问题的直接答案,但很难理解您为什么要在函数中执行某些操作。例如,您这样做:

 x <- as.vector(as.matrix(x))
 results <- x
 x <- Lmin + ((Lmax-Lmin)*x)/Qmax

所以 resultsx 是一个向量,但是你这样做:

if (class(results) == "SpatialGridDataFrame")
#(...)
else if (is.data.frame(x))
#(...)
else results <- x

当我们知道 x 是一个向量(而不是 SpatialGridDataFramedata.frame 时,这有什么关系?这总是会使 results 等于 x。所以很明显,结果将始终是数字。

您声明您这样做:class(results) == "SpatialGridDataFrame",但您并没有这样做。无论哪种方式,这都行不通(这类似于将 post-it 和 "car" 放在你的自行车上;这不会神奇地突然给它四个轮子和一个引擎)。 =26=]

如果您想通过将所有值加载到内存中来加快速度,您可以这样做:

radconvL <- function(x, band = 2) {
     Lmax <- switch(band, 
                    "2" = 120.64,
                    "3" = 151.31,
                    "4" = 157.57,
                    "5" = 69.03,
                    NA)

     if (is.na(Lmax)) stop("invalid band")
     Lmin = 0
     Qmax = 127
     setValues(x, Lmin + ((Lmax-Lmin)*values(x))/Qmax)
}