Skip to content

Help on adding column to shape file

3 messages · Rahul Raj, Barry Rowlingson

#
On Mon, Feb 14, 2011 at 10:47 AM, Rahul Raj <rahulosho at gmail.com> wrote:

            
Assuming v is actually a SpatialPolygonsDataFrame, you can use it in
many ways like a data frame. You can access columns by character
string using [[name]] notation. So here is an example using a point
data set - you should get the same behaviour from polygons:

 > v=data.frame(x=runif(10),y=runif(10),z1=runif(10),z2=runif(10))
 > coordinates(v)=~x+y

 v is now a spatialpointsdataframe. lets' add some columns:

 > v[["z3"]]=1:10
 > v
             coordinates          z1        z2 z3
1    (0.216765, 0.73725) 0.286275825 0.3223297  1
2   (0.171752, 0.569634) 0.606298265 0.3816816  2
3  (0.109809, 0.0321561) 0.548738532 0.2799815  3
4  (0.967817, 0.0313896) 0.662881901 0.6978231  4
5   (0.966963, 0.549404) 0.013866757 0.2950681  5
...
 - that added a column called "z3". to do this in a loop, use 'paste'
to construct the variable name:
coordinates          z1        z2 z3 M1 M2 M3 M4
1    (0.216765, 0.73725) 0.286275825 0.3223297  1  1  2  3  4
2   (0.171752, 0.569634) 0.606298265 0.3816816  2  2  4  6  8
3  (0.109809, 0.0321561) 0.548738532 0.2799815  3  3  6  9 12
4  (0.967817, 0.0313896) 0.662881901 0.6978231  4  4  8 12 16
...

 so now I have my times-tables up to 4 in M1 to M4.
basename(mypath) will get rid off everything up to the last part (but
wont strip Windows \\-separated paths on Linux or MacOS), and then use
sub to get ridd of the extension:

 > mypath="H:/file/gridfile.shp"  # i use forward slashes because I use Linux

 > sub(".shp$","",basename(mypath))
[1] "gridfile"

 - the $ sign matches the end of the string.

Barry