Announcement

Collapse
No announcement yet.
X
  • Filter
  • Time
  • Show
Clear All
new posts

  • Importing .shp file to Stata with "long" varname

    Hello,

    I am trying to import a .shp shapefile containing English local authorities into Stata using shp2dta user written command, but I get an error message saying "long invalid varname" (signalling that the shapefile dataset includes a variable named "long", which is an invalid variable name within Stata - if I have understood correctly).

    Is there a way of amending the varname within the shp2dta command to successfully import it?

    Or is it necessary to use a workaround by e.g. importing into R to rename/delete the variable called "long" (as noted by Carolin Thol in this previous post: https://www.statalist.org/forums/for...files-in-stata)? If anyone has successfully done this and is happy to share steps, that would be much appreciated (I have managed to upload into R, but it does not display like a "normal" dataset so I have not found a way of amending the variable).

    Many thanks!
    Francesca


  • #2
    Hi All,

    Carolin Thol Ioramashvili kindly shared her code for deleting/renaming the variable named long in RStudio. Please see her code with my adaptations below:

    Code:
    # Clear workspace
    rm(list = ls())
    setwd("S:/Maps/LA GPS data/")
    
    # Load packages
    library(sp)
    library(maptools)
    library(sf)
    library(plyr)
    
    
    # Read the shapefile
    
    country <- readShapeSpatial("Local_Authority_Districts_December_2017_Super_Generalised_Clipped_Boundaries_in_Great_Britain.shp")
    
    LA_boundaries <- st_read("S:/Maps/LA GPS data/Local_Authority_Districts_December_2017_Super_Generalised_Clipped_Boundaries_in_Great_Britain.shp")
    st_bbox(aoi_boundary_HARV)
    st_geometry_type(aoi_boundary_HARV)
    
    # Draw the map to check it looks alright
    plot(country)
    
    # Option 1 - Remove the long variable
    # country@data$long <- NULL
    
    # Option 2 - Rename long variable
    names(country)[names(country)=="long"] <- "longi"
    
    # Check it's been changed
    head(country@data)
    
    ogrDrivers()
    
    # Write the new shapefile
    writeOGR(country, dsn = "S:/Maps/LA GPS data/", layer = "newLAboundaries", driver = "ESRI Shapefile"  )

    Additionally, I hadn't realised that in the original forum post Robert Picard had also kindly provided the answer for editing the variable name in Stata (see code from "* fix the database part of the shapefile" to "* convert the database and coordinates part to Stata datasets").
    Thanks, Francesca

    Comment

    Working...
    X