R create spatialpointdataframe code example

Example: R create spatialpointdataframe

library(sp)

dat_orig <- read.table(text="    a    b    c    d    e    lat   lng
 12   f2   23   dd   2d   15.6  80.9
 12   g5   99   NA   hh   20.9  10.9
 13   g4   12   aa   3r3  1.2   81.8", header=TRUE, stringsAsFactors=FALSE)

dat <- dat_orig
coordinates(dat) <- ~lng+lat

dat
##    coordinates  a  b  c    d   e
## 1 (80.9, 15.6) 12 f2 23   dd  2d
## 2 (10.9, 20.9) 12 g5 99 <NA>  hh
## 3  (81.8, 1.2) 13 g4 12   aa 3r3


dat_1 <- dat_orig
colnames(dat_1) <- c(colnames(dat_1)[1:5], "steve", "larry")
coordinates(dat_1) <- ~larry+steve

dat_1
##    coordinates  a  b  c    d   e
## 1 (80.9, 15.6) 12 f2 23   dd  2d
## 2 (10.9, 20.9) 12 g5 99 <NA>  hh
## 3  (81.8, 1.2) 13 g4 12   aa 3r3