How to Convert data frame to spatial coordinates

First, you take the columns of lon and lat and create an object for coord. Then, you subtract them from the original data frame and create a new object. You finally use SpatialPointsDataFrame() to create a SpatialPointsDataFrame. When you create a SpatialPointsDataFrame, you need to assign proj4string. Choose an appropriate one for you.

In your case, you do not have any other columns but lon and lat, the method won’t work. I purposely left lon and lat @data.

DATA

mydf <- structure(list(longitude = c(128.6979, 153.0046, 104.3261, 124.9019, 
126.7328, 153.2439, 142.8673, 152.689), latitude = c(-7.4197, 
-4.7089, -6.7541, 4.7817, 2.1643, -5.65, 23.3882, -5.571)), .Names = c("longitude", 
"latitude"), class = "data.frame", row.names = c(NA, -8L))


### Get long and lat from your data.frame. Make sure that the order is in lon/lat.

xy <- mydf[,c(1,2)]

spdf <- SpatialPointsDataFrame(coords = xy, data = mydf,
                               proj4string = CRS("+proj=longlat +datum=WGS84 +ellps=WGS84 +towgs84=0,0,0"))


#> str(spdf)
#Formal class 'SpatialPointsDataFrame' [package "sp"] with 5 slots
#..@ data       :'data.frame':  8 obs. of  2 variables:
#.. ..$ longitude: num [1:8] 129 153 104 125 127 ...
#.. ..$ latitude : num [1:8] -7.42 -4.71 -6.75 4.78 2.16 ...
#..@ coords.nrs : num(0) 
#..@ coords     : num [1:8, 1:2] 129 153 104 125 127 ...
#.. ..- attr(*, "dimnames")=List of 2
#.. .. ..$ : NULL
#.. .. ..$ : chr [1:2] "longitude" "latitude"
#..@ bbox       : num [1:2, 1:2] 104.33 -7.42 153.24 23.39
#.. ..- attr(*, "dimnames")=List of 2
#.. .. ..$ : chr [1:2] "longitude" "latitude"
#.. .. ..$ : chr [1:2] "min" "max"
#..@ proj4string:Formal class 'CRS' [package "sp"] with 1 slot
#.. .. ..@ projargs: chr "+proj=longlat +datum=WGS84 +ellps=WGS84 +towgs84=0,0,0"

Leave a Comment