代码之家  ›  专栏  ›  技术社区  ›  GCGM

基于R中光栅堆栈像素值的数据帧生成

  •  1
  • GCGM  · 技术社区  · 6 年前

    我正在准备一个数据集来运行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 把它放在盒子里 数据帧

    • 0 ,什么也不做。

    shapefile 使用 extract

    2 回复  |  直到 6 年前
        1
  •  1
  •   Istrel    6 年前

    你可以用 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), ]
    
        2
  •  1
  •   Robert Hijmans    6 年前

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

    如果数据集足够小,可以放入RAM内存,也可以在Istrel建议的路径上选择一个快捷方式:

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