[R-sig-Geo] Help on adding column to shape file

Barry Rowlingson b.rowlingson at lancaster.ac.uk
Mon Feb 14 13:03:27 CET 2011


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

>> v at data$class3 <- 1:nrow(v at data)  ##where v is the object of polygon shape
> file
>
>                                                          ##class3 is the
> column to be added
>
>
>
> Now, I want to add column in loop as
>
>> v at data$classi <- 1:nrow(v at data) ## i = 1,2,3,4,….. Supplied by loop
>
>
>
>  i.e, I want to add column class1, class2, class3….. so on using loop.

 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:

> for(i in 1:4){v[[paste("M",i,sep="")]]=(1:10)*i}
> v
             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.

> My next problem is to extract the name of shape file from selected path.
>
>> shapePath <- choose.files(caption = "Select grid file", filters =
> Filters[c("All"),])
>
>  > shapePath
>
> [1] "H:\\file\\gridfile.shp"
>
>
>
> I want to extract ‘gridfile’ string (without .shp) so that it could directly
> supplied in place of layerFileName in the command written below
>
>> v <- readOGR(shapePath, layer = “layerFileName”)
>
>
>
> Please help to resolve these two issues

 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



More information about the R-sig-Geo mailing list