根据R中的栅格堆栈中的像素值创建数据帧

时间:2018-09-17 09:00:06

标签: r dataframe extract svm

我正在准备运行SVM分类的数据集。到目前为止,我有一个栅格堆栈,其中包括一个用于训练的图层([6]

> S1
class       : RasterStack 
dimensions  : 3865, 6899, 26664635, 6  (nrow, ncol, ncell, nlayers)
resolution  : 14.83, 14.83  (x, y)
extent      : 361363.5, 463675.7, 5760647, 5817965  (xmin, xmax, ymin, ymax)
coord. ref. : +proj=utm +zone=32 +datum=WGS84 +units=m +no_defs +ellps=WGS84 +towgs84=0,0,0 
names       : Coherence_VV_Stack2.1, Coherence_VV_Stack2.2, Coherence_VV_Stack2.3, Coherence_VV_Stack2.4, Coherence_VV_Stack2.5, Class 
min values  :                     ?,                     ?,                     ?,                     ?,                     ?,     0 
max values  :                     ?,                     ?,                     ?,                     ?,                     ?,     1 

S1[[6]]在哪里:

> S1[[6]]
class       : RasterLayer 
dimensions  : 3865, 6899, 26664635  (nrow, ncol, ncell)
resolution  : 14.83, 14.83  (x, y)
extent      : 361363.5, 463675.7, 5760647, 5817965  (xmin, xmax, ymin, ymax)
coord. ref. : +proj=utm +zone=32 +datum=WGS84 +units=m +no_defs +ellps=WGS84 +towgs84=0,0,0 
data source : in memory
names       : Class 
values      : 0, 1  (min, max)

plot(S1[[6])是:

enter image description here

我要创建一个dataframe(稍后用作分类输入),其中:

  • 如果S1[[6]]中的像素值是1,请提取raster stack其他层中的像素值并将其放入dataframe

  • 如果S1[[6]]中的像素值为0,则什么也不做。

关于如何进行的任何建议?我知道可以通过导入shapefile并使用extract函数来解决此问题,但是我想使用这种方法。

2 个答案:

答案 0 :(得分:1)

您可以使用raster::calc

# Prepare function for manipulation with pixels
foo <- function(x){
    # NA case
    if (is.na(x[6])){
        return(NA)
    }
    # If layer 6 is 1
    if (x[6] == 1){
        # Return value from different layer (1 and 2 for example)
        return(x[c(1, 2)])
    } else {
        return(NA)
    }
}

# Use calc to loop over each pixel
new_raster <- calc(S1, foo)

# Convert result to data frame
df <- as.data.frame(new_raster)

# Remove empty values
df <- df[complete.cases(df), ]

答案 1 :(得分:1)

这应该有效

i <- Which(S1[[6]]==1, cells=TRUE)
df <- data.frame(S1[i])

如果数据集足够小以适合RAM内存,您还可以在Istrel建议的路径上使用快捷方式:

df <- as.data.frame(S1) 
df <- df[df[ ,6]== 1, ]