How to change class from data frame to spatial polygon?

前端 未结 1 1486
粉色の甜心
粉色の甜心 2021-01-29 09:07

I have found the same in here How to Convert data frame to spatial coordinates. But in my case, I got very large data.

exchange    longitude   latitude
AB  103.3         


        
相关标签:
1条回答
  • 2021-01-29 09:45

    my data is just the same as the other post [...] So anyone can help me to change classfrom data.frame to spatial polygon?

    library(sp)
    sp <- SpatialPolygons(list(Polygons(list(Polygon(mydf[, -1])), ID=1)))
    class(sp)
    # [1] "SpatialPolygons"
    # attr(,"package")
    # [1] "sp"
    

    or, if you want exchange to be the polygon identifier:

    sp <- lapply(split(mydf[, -1], mydf[, 1]), Polygon)
    sp <- SpatialPolygons(lapply(seq_along(sp), function(i) { 
      Polygons(list(sp[[i]]), ID = row.names(mydf[!duplicated(mydf[, 1]), ])[i] ) 
    }))
    # class(sp)
    # [1] "SpatialPolygons"
    # attr(,"package")
    # [1] "sp"
    

    Data:

    mydf <- read.table(header=T, text="
    exchange   longitude   latitude
    AB  103.3281386 1.594218196
    AB  103.3285929 1.593990735
    AB  103.3312494 1.591424235
    AB  103.3283736 1.594063254
    AB  103.3536164 1.622771588
    AB  103.3613242 1.627138676
    AB  103.3560151 1.619455334
    AB  103.3297071 1.593398614
    AB  103.3269466 1.596574285
    AB  103.3279517 1.593614052
    AB  103.3281356 1.593848271
    AB  103.3567136 1.620498495
    AB  103.3668021 1.63456952
    AB  103.359686  1.624821271
    AB  103.3308963 1.585290892
    AB  103.3319569 1.59104387
    AB  103.3307149 1.592006748
    AB  103.3283657 1.593675616
    AB  103.3314873 1.591186363
    AB  103.3319648 1.590585241
    AB  103.3321508 1.590422594
    AB  103.3318503 1.588685843
    AB  103.3324507 1.594547225
    AB  103.3442528 1.60909707
    AB  103.3292733 1.593461728
    AB  103.3288584 1.594312512
    AB  103.329041  1.594135083
    AB  103.3348961 1.59761749
    AB  103.3500524 1.614224612")
    
    0 讨论(0)
提交回复
热议问题