6

I am interested in iterating through a point shapefile to perform tasks on a point by point basis using R. In Python, this can be accomplished using the following workflow:

import arcpy

shp = r'C:\path\to\shapefile.shp'

with arcpy.da.SearchCursor(shp, ["Field", "SHAPE@"]) as cursor:
    for row in cursor:
        print row[0]
        # Perform some action with row[1] (i.e. the point geometry)

How can I iterate through a point shapefile to access individual point geometry using R?

2
  • Do you have an example of shapefile?
    – user32309
    Commented Sep 9, 2014 at 7:48
  • @Pascal Any point shapefile would do.
    – Aaron
    Commented Sep 9, 2014 at 12:58

2 Answers 2

7

To subset or operate on an individual object all you need is the "row" index, which corresponds to the slots. In this way it is independent of feature class type (i.e., point, polygon, pixel).

# To iterate through the feature class
for(i in 1:nrow(shp)) { p <- shp[i,] }
0
2

Not sure whether it is what you are looking for (it depends on the action you want to perform). For example, let's use a shapefile of populated places.

library(rgdal)

shp <- "C:\path\to\shapefile"    
pts <- readOGR(shp,'ne_10m_populated_places_simple')
OGR data source with driver: ESRI Shapefile 
    Source: "C:\path\to\shapefile", layer: "ne_10m_populated_places_simple"
    with 7322 features and 36 fields
    Feature type: wkbPoint with 2 dimensions

class(pts)
[1] "SpatialPointsDataFrame"
attr(,"package")
[1] "sp"

names(pts)
[1] "scalerank"  "natscale"   "labelrank"  "featurecla" "name"       "namepar"    "namealt"    "diffascii"  "nameascii" 
[10] "adm0cap"    "capalt"     "capin"      "worldcity"  "megacity"   "sov0name"   "sov_a3"     "adm0name"   "adm0_a3"   
[19] "adm1name"   "iso_a2"     "note"       "latitude"   "longitude"  "changed"    "namediff"   "diffnote"   "pop_max"   
[28] "pop_min"    "pop_other"  "rank_max"   "rank_min"   "geonameid"  "meganame"   "ls_name"    "ls_match"   "checkme"

To access the name of the places:

pts$name

head(pts$name)
[1] Colonia del Sacramento Trinidad               Fray Bentos            Canelones              Florida               
[6] Bassar                
7069 Levels: 25 de Mayo 28 de Noviembre Aalborg Aarau Aba Abadan Abadla Abaetetuba Abai Abakan Abancay Abau Abaza ... Zyryanovsk

If you want the associated coordinates:

pts["name"]

pts[1:5,"name"]
         coordinates                   name
1   (-57.84, -34.48) Colonia del Sacramento
2 (-56.901, -33.544)               Trinidad
3 (-58.304, -33.139)            Fray Bentos
4 (-56.284, -34.538)              Canelones
5 (-56.215, -34.099)                Florida

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Not the answer you're looking for? Browse other questions tagged or ask your own question.