【问题标题】:Zonal statistic calculating pixel share and determine the most frequent class in R区域统计计算像素份额并确定 R 中最频繁的类
【发布时间】:2020-01-08 10:38:43
【问题描述】:

我已经在这里发布了一个相关问题:Zonal statistics to get majority pixel value per polygon in R?,但是这次我想确定 SpatialPolygonsDataFrame 中不同多边形中权重份额最高的像素类。 (类似于 QGIS 插件:区域统计 > 多数)出于统计原因,在我的真实数据集中,我想将最后的主要类分配给每个多边形到 @data 插槽。

有一些代码:

set.seed(6)
# Create interger class raster
r <- raster(ncol=36, nrow=18)
r[] <- round(runif(ncell(r),1,10),digits=0)
r[]<-as.integer(r[])
# Create two polygons
cds1 <- rbind(c(-180,-20), c(-160,5), c(-60, 0), c(-160,-60), c(-180,-20))
cds2 <- rbind(c(80,0), c(50,30), c(60,0), c(60,-25))
polys <- SpatialPolygonsDataFrame(SpatialPolygons(list(Polygons(list(Polygon(cds1)), 1), 
Polygons(list(Polygon(cds2)),2))),data.frame(ID=c(1,2)))

# Extract raster values to polygons                             
v <- extract(r, polys, weights = TRUE) 

到目前为止一切都很好,但在下一个问题中,每个列表元素只有一个值向量,因此可以计算频率并确定具有最高份额的类的名称。

这次我在列表中有两列: (列表中的这种数据结构怎么称呼?是矩阵还是列表索引?):

[[1]]
...
[[2]]
     value      weight
[1,]    10 0.066071429
[2,]     9 0.085714286
[3,]     8 0.098214286
[4,]     4 0.026785714
[5,]     4 0.178571429
[6,]     2 0.098214286
[7,]     3 0.178571429
[8,]     2 0.107142857
[9,]     3 0.137500000
[10,]     3 0.005357143
[11,]     6 0.017857143

我将如何运行例如dplyr::group_by()summarise()。我用dplyr::summarize_at 尝试了不同的方法,但我很困惑如何处理这种数据类型。

【问题讨论】:

    标签: r r-raster


    【解决方案1】:

    v 列表的主要问题是每个条目都是一个类 matrix 对象。因此,您需要将每个列表条目转换为data.frame,然后才能使用dplyr 函数。

    library(dplyr)
    
    #Each entry in the list is a matrix object
    class(v[[1]])
    #[1] "matrix"
    
    #Thus, you need to transform every entry to data.frame
    v<-lapply(v, function(x) as.data.frame(x))
    #Then set a name for every list entry, in order to use bind_rows
    names(v)<-c("1","2")
    #use bind_rows
    df<-bind_rows(v, .id = "id")
    #Get the most frequent class and its frequency
    df %>%
      group_by(id,value) %>%
      count() %>%
      ungroup()%>%
      group_by(id)%>%
      summarize(most_freqclass = value[which(n == max(n))],
                max_freq = max(n))
    

    【讨论】:

    • 谢谢你,这正是我需要的!
    • 也许是关于分组部分的一个小注释,我将代码修改为:x&lt;-df %&gt;% group_by(id,value) %&gt;% count()%&gt;% ungroup() #Omit cases where share of pixel values has the same amount x[!duplicated(x[,c("id","n")]),]%&gt;% group_by(id)%&gt;% summarize(most_freqclass = value[which(n == max(n))], max_freq = max(n)) 因为在我的数据集中,碰巧我在一个多边形中拥有相同的像素值份额,而 dplyr::summarize 可以正常工作具有独特的价值。
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2018-12-10
    • 2023-01-05
    • 1970-01-01
    相关资源
    最近更新 更多