AskOverflow.Dev

AskOverflow.Dev Logo AskOverflow.Dev Logo

AskOverflow.Dev Navigation

  • Início
  • system&network
  • Ubuntu
  • Unix
  • DBA
  • Computer
  • Coding
  • LangChain

Mobile menu

Close
  • Início
  • system&network
    • Recentes
    • Highest score
    • tags
  • Ubuntu
    • Recentes
    • Highest score
    • tags
  • Unix
    • Recentes
    • tags
  • DBA
    • Recentes
    • tags
  • Computer
    • Recentes
    • tags
  • Coding
    • Recentes
    • tags
Início / coding / Perguntas / 79544779
Accepted
Ilik
Ilik
Asked: 2025-03-30 23:08:28 +0800 CST2025-03-30 23:08:28 +0800 CST 2025-03-30 23:08:28 +0800 CST

Defina a projeção de SpatialPolygonsDataFrame usando o pacote sf

  • 772

Estou atualizando o código rgdalpara usar o sfpacote.

Tenho um SpatialPolygonsDataFrame que preciso projetar. Em rgdaleu usei proj4string(). Com sf, tentei usar st_crs():

library(sf)
ext <- extent(c(0, 20, 0, 20))
r <- raster(ext, res=1)  
r[] = 1:ncell(r)

# convert the raster to polygon:
Output_Shapefile <- rasterToPolygons(r) 

prj <- "+proj=eqdc +lat_0=17.8333333333333 +lon_0=-66.4333333333333 +lat_1=18.4333333333333 +lat_2=18.0333333333333 +x_0=200000 +y_0=200000 +ellps=GRS80 +towgs84=0,0,0,0,0,0,0 +units=m +no_defs"

#project:
#  proj4string(Output_Shapefile) <- prj


st_crs(Output_Shapefile) <- prj

Aqui está o erro que estou recebendo:

Error in UseMethod("st_crs<-") : 
  no applicable method for 'st_crs<-' applied to an object of class "c('SpatialPolygonsDataFrame', 'SpatialPolygons', 'Spatial', 'SpatialVector')"
  • 2 2 respostas
  • 73 Views

2 respostas

  • Voted
  1. Best Answer
    dieghernan
    2025-03-31T01:09:54+08:002025-03-31T01:09:54+08:00

    Primeiro, considere trabalhar completamente com sf e evite usar sp, pois o sp está em modo de manutenção no momento.

    A solução é converter SpatialPolygonsDataFramepara sf, atribuir o crs e voltar para SpatialPolygonsDataFrame:

    library(sf)
    #> Linking to GEOS 3.12.1, GDAL 3.8.4, PROJ 9.3.1; sf_use_s2() is TRUE
    library(raster)
    #> Cargando paquete requerido: sp
    ext <- extent(c(0, 20, 0, 20))
    r <- raster(ext, res = 1)
    r[] <- 1:ncell(r)
    
    # convert the raster to polygon:
    Output_Shapefile <- rasterToPolygons(r)
    
    prj <- "+proj=eqdc +lat_0=17.8333333333333 +lon_0=-66.4333333333333 +lat_1=18.4333333333333 +lat_2=18.0333333333333 +x_0=200000 +y_0=200000 +ellps=GRS80 +towgs84=0,0,0,0,0,0,0 +units=m +no_defs"
    
    # project:
    #  proj4string(Output_Shapefile) <- prj
    
    
    st_crs(Output_Shapefile) <- prj
    #> Error in UseMethod("st_crs<-"): no applicable method for 'st_crs<-' applied to an object of class "c('SpatialPolygonsDataFrame', 'SpatialPolygons', 'Spatial', 'SpatialVector')"
    

    E aqui está a solução:

    
    ## Solution
    
    # Object with no sp
    Output_Shapefile
    #> class       : SpatialPolygonsDataFrame 
    #> features    : 400 
    #> extent      : 0, 20, 0, 20  (xmin, xmax, ymin, ymax)
    #> crs         : NA 
    #> variables   : 1
    #> names       : layer 
    #> min values  :     1 
    #> max values  :   400
    
    # Instead do
    Output_Shapefile_sf <- st_as_sf(Output_Shapefile)
    Output_Shapefile_sf
    #> Simple feature collection with 400 features and 1 field
    #> Geometry type: POLYGON
    #> Dimension:     XY
    #> Bounding box:  xmin: 0 ymin: 0 xmax: 20 ymax: 20
    #> CRS:           NA
    #> First 10 features:
    #>    layer                       geometry
    #> 1      1 POLYGON ((0 20, 1 20, 1 19,...
    #> 2      2 POLYGON ((1 20, 2 20, 2 19,...
    #> 3      3 POLYGON ((2 20, 3 20, 3 19,...
    #> 4      4 POLYGON ((3 20, 4 20, 4 19,...
    #> 5      5 POLYGON ((4 20, 5 20, 5 19,...
    #> 6      6 POLYGON ((5 20, 6 20, 6 19,...
    #> 7      7 POLYGON ((6 20, 7 20, 7 19,...
    #> 8      8 POLYGON ((7 20, 8 20, 8 19,...
    #> 9      9 POLYGON ((8 20, 9 20, 9 19,...
    #> 10    10 POLYGON ((9 20, 10 20, 10 1...
    st_crs(Output_Shapefile_sf) <- prj
    Output_Shapefile_sf
    #> Simple feature collection with 400 features and 1 field
    #> Geometry type: POLYGON
    #> Dimension:     XY
    #> Bounding box:  xmin: 0 ymin: 0 xmax: 20 ymax: 20
    #> Projected CRS: +proj=eqdc +lat_0=17.8333333333333 +lon_0=-66.4333333333333 +lat_1=18.4333333333333 +lat_2=18.0333333333333 +x_0=200000 +y_0=200000 +ellps=GRS80 +towgs84=0,0,0,0,0,0,0 +units=m +no_defs
    #> First 10 features:
    #>    layer                       geometry
    #> 1      1 POLYGON ((0 20, 1 20, 1 19,...
    #> 2      2 POLYGON ((1 20, 2 20, 2 19,...
    #> 3      3 POLYGON ((2 20, 3 20, 3 19,...
    #> 4      4 POLYGON ((3 20, 4 20, 4 19,...
    #> 5      5 POLYGON ((4 20, 5 20, 5 19,...
    #> 6      6 POLYGON ((5 20, 6 20, 6 19,...
    #> 7      7 POLYGON ((6 20, 7 20, 7 19,...
    #> 8      8 POLYGON ((7 20, 8 20, 8 19,...
    #> 9      9 POLYGON ((8 20, 9 20, 9 19,...
    #> 10    10 POLYGON ((9 20, 10 20, 10 1...
    
    # Back to sp
    Output_Shapefile <- as(Output_Shapefile_sf, "Spatial")
    
    Output_Shapefile
    #> class       : SpatialPolygonsDataFrame 
    #> features    : 400 
    #> extent      : 0, 20, 0, 20  (xmin, xmax, ymin, ymax)
    #> crs         : +proj=eqdc +lat_0=17.8333333333333 +lon_0=-66.4333333333333 +lat_1=18.4333333333333 +lat_2=18.0333333333333 +x_0=200000 +y_0=200000 +ellps=GRS80 +towgs84=0,0,0,0,0,0,0 +units=m +no_defs 
    #> variables   : 1
    #> names       : layer 
    #> min values  :     1 
    #> max values  :   400
    

    Criado em 2025-03-30 com reprex v2.1.1

    • 1
  2. Robert Hijmans
    2025-03-31T11:42:36+08:002025-03-31T11:42:36+08:00

    Como você está migrando para "sf", faz sentido também deixar "raster" para trás e usar "terra".

    library(terra)
    ext <- ext(c(0, 20, 0, 20))
    prj <- "+proj=eqdc +lat_0=17.8333333333333 +lon_0=-66.4333333333333 +lat_1=18.4333333333333 +lat_2=18.0333333333333 +x_0=200000 +y_0=200000 +ellps=GRS80 +towgs84=0,0,0,0,0,0,0 +units=m +no_defs"
    r <- rast(ext, res=1, crs=prj)  
    values(r) = 1:ncell(r)
    
    # you can do 
    pols <- as.polygons(r) 
    sf1 <- sf::st_as_sf(pols)
    sf1::st_transform(sf1, "+proj=longlat")
    
    #or 
    p <- project(pols, "+proj=longlat")
    sf2 <- sf::st_as_sf(pols)
    
    • 1

relate perguntas

  • Adicionar número de série para atividade de cópia ao blob

  • A fonte dinâmica do empacotador duplica artefatos

  • Selecione linhas por grupo com 1s consecutivos

  • Lista de chamada de API de gráfico subscritoSkus estados Privilégios insuficientes enquanto os privilégios são concedidos

  • Função para criar DFs separados com base no valor da coluna

Sidebar

Stats

  • Perguntas 205573
  • respostas 270741
  • best respostas 135370
  • utilizador 68524
  • Highest score
  • respostas
  • Marko Smith

    Reformatar números, inserindo separadores em posições fixas

    • 6 respostas
  • Marko Smith

    Por que os conceitos do C++20 causam erros de restrição cíclica, enquanto o SFINAE antigo não?

    • 2 respostas
  • Marko Smith

    Problema com extensão desinstalada automaticamente do VScode (tema Material)

    • 2 respostas
  • Marko Smith

    Vue 3: Erro na criação "Identificador esperado, mas encontrado 'import'" [duplicado]

    • 1 respostas
  • Marko Smith

    Qual é o propósito de `enum class` com um tipo subjacente especificado, mas sem enumeradores?

    • 1 respostas
  • Marko Smith

    Como faço para corrigir um erro MODULE_NOT_FOUND para um módulo que não importei manualmente?

    • 6 respostas
  • Marko Smith

    `(expression, lvalue) = rvalue` é uma atribuição válida em C ou C++? Por que alguns compiladores aceitam/rejeitam isso?

    • 3 respostas
  • Marko Smith

    Um programa vazio que não faz nada em C++ precisa de um heap de 204 KB, mas não em C

    • 1 respostas
  • Marko Smith

    PowerBI atualmente quebrado com BigQuery: problema de driver Simba com atualização do Windows

    • 2 respostas
  • Marko Smith

    AdMob: MobileAds.initialize() - "java.lang.Integer não pode ser convertido em java.lang.String" para alguns dispositivos

    • 1 respostas
  • Martin Hope
    Fantastic Mr Fox Somente o tipo copiável não é aceito na implementação std::vector do MSVC 2025-04-23 06:40:49 +0800 CST
  • Martin Hope
    Howard Hinnant Encontre o próximo dia da semana usando o cronógrafo 2025-04-21 08:30:25 +0800 CST
  • Martin Hope
    Fedor O inicializador de membro do construtor pode incluir a inicialização de outro membro? 2025-04-15 01:01:44 +0800 CST
  • Martin Hope
    Petr Filipský Por que os conceitos do C++20 causam erros de restrição cíclica, enquanto o SFINAE antigo não? 2025-03-23 21:39:40 +0800 CST
  • Martin Hope
    Catskul O C++20 mudou para permitir a conversão de `type(&)[N]` de matriz de limites conhecidos para `type(&)[]` de matriz de limites desconhecidos? 2025-03-04 06:57:53 +0800 CST
  • Martin Hope
    Stefan Pochmann Como/por que {2,3,10} e {x,3,10} com x=2 são ordenados de forma diferente? 2025-01-13 23:24:07 +0800 CST
  • Martin Hope
    Chad Feller O ponto e vírgula agora é opcional em condicionais bash com [[ .. ]] na versão 5.2? 2024-10-21 05:50:33 +0800 CST
  • Martin Hope
    Wrench Por que um traço duplo (--) faz com que esta cláusula MariaDB seja avaliada como verdadeira? 2024-05-05 13:37:20 +0800 CST
  • Martin Hope
    Waket Zheng Por que `dict(id=1, **{'id': 2})` às vezes gera `KeyError: 'id'` em vez de um TypeError? 2024-05-04 14:19:19 +0800 CST
  • Martin Hope
    user924 AdMob: MobileAds.initialize() - "java.lang.Integer não pode ser convertido em java.lang.String" para alguns dispositivos 2024-03-20 03:12:31 +0800 CST

Hot tag

python javascript c++ c# java typescript sql reactjs html

Explore

  • Início
  • Perguntas
    • Recentes
    • Highest score
  • tag
  • help

Footer

AskOverflow.Dev

About Us

  • About Us
  • Contact Us

Legal Stuff

  • Privacy Policy

Language

  • Pt
  • Server
  • Unix

© 2023 AskOverflow.DEV All Rights Reserve