Cannot output spatial dataframe to .shp - r

I've used gConvexHull() to create a home range polygon that is classed as an SP polygon. In order to output as an .shp file, I converted it to a SpatialPolygonsDataFrame and its new class is "sf" "data.frame".
But when I try to output it using writeOGR(), it comes up with the error message:
Error in writeOGR(obj = HRDF, dsn = "C:/Users/RKirton/Documents/Data files", :
inherits(obj, "Spatial") is not TRUE
I also tried st_write() and got this new error message:
Error in CPL_write_ogr(obj, dsn, layer, driver, as.character(dataset_options), :
argument dsn, layer or driver not of length 1.
I'm fairly new to R and am unsure how to resolve these error messages.
Here is my code:
for(i in 1:length(unique(mydata$ID))) {
hunt <- mydata[which(mydata$Season2 == "Hunt" & mydata$ID ==
unique(mydata$ID)[i]), ]
hunt_spdf <- SpatialPointsDataFrame(coords = cbind(hunt$X, hunt$Y), data =
hunt, proj4string = CRS("+init=epsg:32614"))
HR = gConvexHull(hunt_spdf, byid = FALSE)
plot(hunt_spdf)
plot(HR, add = TRUE)
HRDF = SpatialPolygonsDataFrame(HR, data = data.frame(IDs="Deer_HHR"))
HRDF = st_as_sf(HR)
HRDF
HRDF$NEWCOL = "ID"
HRDF
st_write(obj = HRDF, dsn="C:/Users/RKirton/Documents/Data files",
layer=paste0('DeerHHR_', hunt$ID), driver="ESRI Shapefile")
}

If you want to tag someone in a comment you need to use the # symbol, as in #SymbolixAU, then they'll get notified.
Also, it's hard to find the errors in your code without having a reproducible example.
To try and help, here's a working example of creating an sf object from a data.frame, then finding the convex hull, then saving the .shp file(s) to a directory. If you want specific help you need to supply some data for others to work with.
This example is only using sf objects, not sp
library(sf)
library(sfheaders)
## An example data.frame
df <- data.frame(
id = c( rep(1, 15), rep(2, 11))
, x = rnorm(26)
, y = rnorm(26)
)
sf <- sfheaders::sf_multipoint(obj = df, multipoint_id = "id", x = "x", y = "y")
sf <- sf::st_set_crs( sf, 32614 )
sf
# Simple feature collection with 2 features and 1 field
# geometry type: MULTIPOINT
# dimension: XY
# bbox: xmin: 1 ymin: 1 xmax: 26 ymax: 26
# z_range: zmin: NA zmax: NA
# m_range: mmin: NA mmax: NA
# epsg (SRID): 32614
# proj4string: +proj=utm +zone=14 +datum=WGS84 +units=m +no_defs
# id geometry
# 1 1 MULTIPOINT (1 26, 2 25, 3 2...
# 2 2 MULTIPOINT (16 11, 17 10, 1...
sf_hull <- sf::st_convex_hull( sf )
sf_hull
sf::st_write( obj = sf_hull, dsn = "~/Desktop/my_hull_dir/my_hull.shp")

Related

raster::rasterToContour; contour lines are not continuous

I am trying to extract contour lines from a raster object using the raster package in R.
rasterToContour appears to work well and plots nicely, but when investigated it appears the contour lines are broken up into irregular segments. Example data from ?rasterToContour
library(raster)
f <- system.file("external/test.grd", package="raster")
r <- raster(f)
x <- rasterToContour(r)
class(x)
plot(r)
plot(x, add=TRUE)
I am trying to extract the contour line of a sample site in the raster. So, we choose a random site, extract its elevation, and run rasterToContour() again, specifying the elevation for the contour line level.
# our sample site - a random cell chosen on the raster
xyFromCell(r, 5000) %>%
SpatialPoints(proj4string = crs(r)) %>%
{. ->> site_sp} %>%
st_as_sf %>%
{. ->> site_sf}
# find elevation of sample site, and extract contour lines
extract(r, site_sf) %>%
{. ->> site_elevation}
# extract contour lines
r %>%
rasterToContour(levels = site_elevation) %>%
{. ->> contours_sp} %>%
st_as_sf %>%
{. ->> contours_sf}
# plot the site and new contour lines (approx elevation 326)
plot(r)
plot(contours_sf, add = TRUE)
plot(site_sf, add = TRUE)
# plot the contour lines and sample site - using sf and ggplot
ggplot()+
geom_sf(data = contours_sf)+
geom_sf(data = site_sf, color = 'red')
Then we use st_intersects to find the lines that intersect the site (with a buffer width of 100 to ensure it touches the line). But, this returns all of the contour lines.
contours_sf %>%
filter(
st_intersects(., site_sf %>% st_buffer(100), sparse = FALSE)[1,]
) %>%
ggplot()+
geom_sf()
I assume all lines are returned because they appear to be a single MULTILINESTRING sf object.
contours_sf
# Simple feature collection with 1 feature and 1 field
# geometry type: MULTILINESTRING
# dimension: XY
# bbox: xmin: 178923.1 ymin: 329720 xmax: 181460 ymax: 333412.3
# CRS: +proj=sterea +lat_0=52.1561605555556 +lon_0=5.38763888888889 +k=0.9999079 +x_0=155000 +y_0=463000 +datum=WGS84 +units=m +no_defs
# level geometry
# C_1 326.849822998047 MULTILINESTRING ((179619.3 ...
So, I have split the contours_sf MULTILINESTRING into individual lines using ngeo::st_segments() (I couldn't find any sf way to do this, but am open to using alternative methods, especially if this is the problem).
Unexpectedly this returns 394 features; from looking at the figure I would expect approximately 15 separate lines.
contours_sf %>%
nngeo::st_segments()
# Simple feature collection with 394 features and 1 field
# geometry type: LINESTRING
# dimension: XY
# bbox: xmin: 178923.1 ymin: 329720 xmax: 181460 ymax: 333412.3
# CRS: +proj=sterea +lat_0=52.1561605555556 +lon_0=5.38763888888889 +k=0.9999079 +x_0=155000 +y_0=463000 +datum=WGS84 +units=m +no_defs
# First 10 features:
# level result
# 1 326.849822998047 LINESTRING (179619.3 329739...
# 2 326.849822998047 LINESTRING (179580 329720.4...
# 3 326.849822998047 LINESTRING (179540 329720, ...
# 4 326.849822998047 LINESTRING (179500 329735.8...
# 5 326.849822998047 LINESTRING (179495.3 329740...
# 6 326.849822998047 LINESTRING (179460 329764, ...
# 7 326.849822998047 LINESTRING (179442.6 329780...
# 8 326.849822998047 LINESTRING (179420 329810, ...
# 9 326.849822998047 LINESTRING (179410.2 329820...
# 10 326.849822998047 LINESTRING (179380 329847.3...
Then, when we filter to keep only the lines which intersect the site (with a buffer width of 100), only a small section of the expected contour line is returned (red section of line, I assume reflective of the 100 buffer width).
contours_sf %>%
nngeo::st_segments() %>%
filter(
# this syntax used as recommended by this answer https://stackoverflow.com/a/57025700/13478749
st_intersects(., site_sf %>% st_buffer(100), sparse = FALSE)
) %>%
ggplot()+
geom_sf(colour = 'red', size = 3)+
geom_sf(data = contours_sf)+
geom_sf(data = site_sf, colour = 'cyan')+
geom_sf(data = site_sf %>% st_buffer(100), colour = 'cyan', fill = NA)
Anyone got ideas for the following points:
Explain why the contour lines are 'broken'
Provide an efficient method for 'joining' the broken pieces together
An alternative to nngeo::st_segments(), if this is in fact the source of the 394 lines not ~15
Converting the MULTILINESTRING to a LINESTRING seems to do what you need:
contours_sf %>% st_cast("LINESTRING") %>%
filter(st_intersects(., st_buffer(site_sf, 100), sparse=FALSE)[,1]) %>%
ggplot()+
geom_sf(data = contours_sf)+
geom_sf(data = site_sf, color = 'red') +
geom_sf(color = 'pink')
Perhaps it works better if you start by disaggregating the lines
library(raster)
f <- system.file("external/test.grd", package="raster")
r <- raster(f)
x <- rasterToContour(r)
x <- disaggregate(x)
Or with terra
library(terra)
r <- rast(f)
x <- as.contour(r)
x
# class : SpatVector
# geometry : lines
# dimensions : 8, 1 (geometries, attributes)
x <- disaggregate(x)
x
# class : SpatVector
# geometry : lines
# dimensions : 56, 1 (geometries, attributes)
And you can continue like this
y <- st_as_sf(x)
Or like this
r <- rast(system.file("ex/meuse.tif", package="terra"))
site <- vect(xyFromCell(r, 5000), crs=crs(r))
elevation <- extract(r, site)
v <- disaggregate(as.contour(r, levels=elevation))
i <- which.min(distance(site, v))
vv <- v[i]
plot(r)
lines(v)
lines(vv, col="red", lwd=2)
points(site, col="blue", cex=2)

Unknown CRS in QGIS when projecting to EPSG:25833 in R

I want to project a spatial data frame to EPSG 25833 in R but QGIS does not seem to know it (for reproducibility, I use the code jazzurro created in his/her answer to this question with minor changes)
library(rgdal)
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)]
# Here I use the projection EPSG:25833
spdf <- SpatialPointsDataFrame(coords = xy, data = mydf,
proj4string = CRS("+proj=utm +zone=33 +ellps=GRS80 +towgs84=0,0,0,0,0,0,0 +units=m +no_defs"))
#Export as shapefile
writeOGR(spdf, "file location", "proj_test", driver="ESRI Shapefile",overwrite_layer = T) #now I write the subsetted network as a shapefile again
Now when I load the shapefile into QGIS it doesn´t know the projection.
Any ideas?
In making your SpatialPointsDataFrame:
# Wrong!
spdf <- SpatialPointsDataFrame(coords = xy, data = mydf,
proj4string = CRS("+proj=utm +zone=33 +ellps=GRS80 +towgs84=0,0,0,0,0,0,0 +units=m +no_defs"))`
You are telling the data frame what crs your points are in, so you should specify 4326 since your original data is lon/lat.
So it should be:
spdf <- SpatialPointsDataFrame(coords = xy, data = mydf,
proj4string = CRS("+proj=longlat +datum=WGS84"))
And then you can transform the data to another CRS using spTransform:
spTransform(spdf, CRS('+proj=utm +zone=33 +ellps=GRS80 +towgs84=0,0,0,0,0,0,0 +units=m +no_defs'))
For this particular data, we get an error because one of the points doesn't convert to your target CRS:
Error in spTransform(xSP, CRSobj, ...) : failure in points 3 In
addition: Warning message: In spTransform(xSP, CRSobj, ...) : 1
projected point(s) not finite
I prefer working in sf so we could also do:
library(sf)
sfdf <- st_as_sf(mydf, coords = c('longitude', 'latitude'), crs=4326, remove=F)
sfdf_25833 <- sfdf %>% st_transform(25833)
sfdf_25833
#> Simple feature collection with 8 features and 2 fields (with 1 geometry empty)
#> geometry type: POINT
#> dimension: XY
#> bbox: xmin: 5589731 ymin: -19294970 xmax: 11478870 ymax: 19337710
#> epsg (SRID): 25833
#> proj4string: +proj=utm +zone=33 +ellps=GRS80 +towgs84=0,0,0,0,0,0,0 +units=m +no_defs
#> longitude latitude geometry
#> 1 128.6979 -7.4197 POINT (10198485 -17980649)
#> 2 153.0046 -4.7089 POINT (5636527 -19294974)
#> 3 104.3261 -6.7541 POINT EMPTY
#> 4 124.9019 4.7817 POINT (11478868 18432292)
#> 5 126.7328 2.1643 POINT (11046583 19337712)
#> 6 153.2439 -5.6500 POINT (5589731 -19158700)
#> 7 142.8673 23.3882 POINT (6353660 16093116)
#> 8 152.6890 -5.5710 POINT (5673080 -19163103)
and you can write and open with QGIS using:
write_sf(sfdf_25833, 'mysf.gpkg')

Creating sf object from dataframe (UTM)

I am new to the sf package in r attempting to create an object from a set of points gives to me in UTM by a collaborator. I've seen how people can use similar methods with lat/long coordinates but have not been able to achieve the same results because of the zone portion of point definitions
can.df <- data.frame(
rbind(
c("NW", "9V", 586518, 7077103),
c("NE", "13W", 645544, 7118728),
c("SW", "11T", 680262, 4865141),
c("SE", "14T", 314095, 497555)),
stringsAsFactors = F)
colnames(can.df) <- c("Corner", "Zone", "Northing", "Easting")
## make xy numeric
num.cols <- c("Northing", "Easting")
can.df[num.cols] <- sapply(can.df[num.cols], as.numeric)
can.df["Zone"] <- as.character(can.df["Zone"])
test <- st_as_sf(can.df,
coords = c("Easting", "Northing", "Zone"),
epsg = 2955)
This will give me the error:
Error in points_cpp(pts, gdim): Not compatible with requested type:
[type=character; target=double].
and if I strip the letters from the zone definition, and use it as numeric. Then I receive:
Error in st_sf(x, ..., agr = agr, sf_column_name = sf_column_name): no
simple features geometry column present
Can anyone shed some light as to what I'm missing?
Try removing "Zone" form coords and change epsg to crs. epsg is not a parameter accepted by st_sf.
library(sf)
#> Linking to GEOS 3.8.0, GDAL 3.0.1, PROJ 6.2.0
can.df <- data.frame(
rbind(
c("NW", "9V", 586518, 7077103),
c("NE", "13W", 645544, 7118728),
c("SW", "11T", 680262, 4865141),
c("SE", "14T", 314095, 497555)),
stringsAsFactors = F)
colnames(can.df) <- c("Corner", "Zone", "Northing", "Easting")
## make xy numeric
num.cols <- c("Northing", "Easting")
can.df[num.cols] <- sapply(can.df[num.cols], as.numeric)
can.df["Zone"] <- as.character(can.df["Zone"])
test <- st_as_sf(can.df,
coords = c("Easting", "Northing", "Zone"),
crs = 2955)
#> Warning in lapply(x[coords], as.numeric): NAs introduced by coercion
#> Error in st_as_sf.data.frame(can.df, coords = c("Easting", "Northing", : missing values in coordinates not allowed
test <- st_as_sf(can.df,
coords = c("Easting", "Northing"),
crs = 2955)
test
#> Simple feature collection with 4 features and 2 fields
#> geometry type: POINT
#> dimension: XY
#> bbox: xmin: 497555 ymin: 314095 xmax: 7118728 ymax: 680262
#> epsg (SRID): 2955
#> proj4string: +proj=utm +zone=11 +ellps=GRS80 +towgs84=0,0,0,0,0,0,0 +units=m +no_defs
#> Corner Zone geometry
#> 1 NW c("9V", "13W", "11T", "14T") POINT (7077103 586518)
#> 2 NE c("9V", "13W", "11T", "14T") POINT (7118728 645544)
#> 3 SW c("9V", "13W", "11T", "14T") POINT (4865141 680262)
#> 4 SE c("9V", "13W", "11T", "14T") POINT (497555 314095)
Created on 2019-10-15 by the reprex package (v0.3.0)

Memory (RAM) issues using intersect from raster package

I have trouble getting the intersection between two large SpatialPolygonsDataFrame on R. My polygons data represent buildings and administrative boundaries, and I am trying to get the intersection polygons between them.
I understand that the intersect function from the raster package and gIntersection from the rgeos package can do this job (with a few differences) but they cannot handle all my polygons at once (about 50.000 polygons/entity).
For this reason, I have to split my calculation within a loop, saving the result for each step. The problem is: these functions keep filling my physical memory, and I cannot clean it. I tried using rm() and gc(), but it does not change a thing. The memory issue crashes my R session, and I cannot do my calculation.
Is there a way to free the RAM during simulation, within loops ? Or to avoid this memory issue ?
Here comes a reproducible example, for random polygons.
library(raster)
library(sp)
library(rgeos)
#Generating 50000 points (for smaller polygons) and 150000 (for larger polygons) in a square of side 100000
size=100000
Nb_points1=50000
Nb_points2=150000
start_point=matrix(c(sample(x = 1:size,size = Nb_points1,replace = T),sample(x = 1:size,size = Nb_points1,replace = T)),ncol=2)
start_point2=matrix(c(sample(x = 1:size,size = Nb_points2,replace = T),sample(x = 1:size,size = Nb_points2,replace = T)),ncol=2)
#Defining different sides length
radius=sample(x = 1:50,size = Nb_points1,replace = T)
radius2=sample(x = 1:150,size = Nb_points2,replace = T)
#Generating list of polygons coordinates
coords=list()
for(y in 1:Nb_points1){
xmin=max(0,start_point[y,1]-radius[y])
xmax=min(size,start_point[y,1]+radius[y])
ymin=max(0,start_point[y,2]-radius[y])
ymax=min(size,start_point[y,2]+radius[y])
coords[[y]]=matrix(c(xmin,xmin,xmax,xmax,ymin,ymax,ymax,ymin),ncol=2)
}
coords2=list()
for(y in 1:Nb_points2){
xmin=max(0,start_point2[y,1]-radius2[y])
xmax=min(size,start_point2[y,1]+radius2[y])
ymin=max(0,start_point2[y,2]-radius2[y])
ymax=min(size,start_point2[y,2]+radius2[y])
coords2[[y]]=matrix(c(xmin,xmin,xmax,xmax,ymin,ymax,ymax,ymin),ncol=2)
}
#Generating 75000 polygons
Poly=SpatialPolygons(Srl = lapply(1:Nb_points1,function(y) Polygons(srl = list(Polygon(coords=coords[y],hole = F)),ID = y)),proj4string = CRS('+init=epsg:2154'))
Poly2=SpatialPolygons(Srl = lapply(1:Nb_points2,function(y)Polygons(srl = list(Polygon(coords=coords2[y],hole = F)),ID = y)),proj4string = CRS('+init=epsg:2154'))
#Union of overlapping polygons
aaa=gUnionCascaded(Poly)
bbb=gUnionCascaded(Poly2)
aaa=disaggregate(aaa)
bbb=disaggregate(bbb)
intersection=gIntersects(spgeom1 = aaa,bbb,byid = T,returnDense = F)
#Loop on the intersect function
pb <- txtProgressBar(min = 0, max = ceiling(length(aaa)/1000), style = 3)
for(j in 1:ceiling(length(aaa)/1000)){
tmp_aaa=aaa[((j-1)*1000+1):(j*1000),]
tmp_bbb=bbb[unique(unlist(intersection[((j-1)*1000+1):(j*1000)])),]
List_inter=intersect(tmp_aaa,tmp_bbb)
gc()
gc()
gc()
setTxtProgressBar(pb, j)
}
Thank you !
You can consider using the st_intersects and st_intersection functions of package sf. For example:
aaa2 <- sf::st_as_sf(aaa)
bbb2 <- sf::st_as_sf(bbb)
intersections_mat <- sf::st_intersects(aaa2, bbb2)
intersections <- list()
for (int in seq_along(intersections_mat)){
if (length(intersections_mat[[int]]) != 0){
intersections[[int]] <- sf::st_intersection(aaa2[int,],
bbb2[intersections_mat[[int]],])
}
}
will give you an intersection_mat of length equal to aaa, and containing , for each feature of aaa, the "indexes" of bbb elements with which it intersects ("empty" if no intersection found):
> intersections_mat
Sparse geometry binary predicate list of length 48503, where the predicate was `intersects'
first 10 elements:
1: 562
2: (empty)
3: 571
4: 731
5: (empty)
6: (empty)
7: (empty)
8: 589
9: 715
10: (empty)
, and an intersection list containing the list of intersecting polygons:
>head(intersections)
[[1]]
Simple feature collection with 1 feature and 0 fields
geometry type: POLYGON
dimension: XY
bbox: xmin: 98873 ymin: 33 xmax: 98946 ymax: 98
epsg (SRID): 2154
proj4string: +proj=lcc +lat_1=49 +lat_2=44 +lat_0=46.5 +lon_0=3 +x_0=700000 +y_0=6600000 +ellps=GRS80 +towgs84=0,0,0,0,0,0,0 +units=m +no_defs
geometry
1 POLYGON ((98873 33, 98873 9...
[[2]]
NULL
[[3]]
Simple feature collection with 1 feature and 0 fields
geometry type: POLYGON
dimension: XY
bbox: xmin: 11792 ymin: 3 xmax: 11806 ymax: 17
epsg (SRID): 2154
proj4string: +proj=lcc +lat_1=49 +lat_2=44 +lat_0=46.5 +lon_0=3 +x_0=700000 +y_0=6600000 +ellps=GRS80 +towgs84=0,0,0,0,0,0,0 +units=m +no_defs
geometry
1 POLYGON ((11792 3, 11792 17...
(i.e., intersections[[1]] is the intersection between polygon 1 of aaa and polygon 571 of bbb)
HTH.
The example works fine for me (8 GB RAM), after a few changes to the loop. See below. Tese changes are not related to memory use --- you were not storing the results.
List_inter <- list()
for(j in 1:ceiling(length(aaa)/1000)){
begin <- (j-1) * 1000 + 1
end <- min((j*1000), length(aaa))
tmp_aaa <- aaa[begin:end,]
tmp_bbb <- bbb[unique(unlist(intersection[begin:end])),]
List_inter[[j]] <- intersect(tmp_aaa,tmp_bbb)
cat(j, "\n"); flush.console()
}
x <- do.call(bind, List_inter)
Alternatively, you could write the intermediate results to disk, and deal with them later:
inters <- intersect(tmp_aaa,tmp_bbb)
saveRDS(inters, paste0(j, '.rds'))
Or
shapefile(inters, paste0(j, '.shp'))

Switching between two CRS in R (with rgdal)

I'm (trying to) do operations on pairs of geographical points. I have the coordinates of my points in WGS84, and I need to have them in the Lambert 2 Extended CRS (LIIE). I'm trying to do it using rgdal.
Here's what I'm doing :
library("rgdal")
library("sp")
# Loading CRS
WGS84<-"+proj=longlat +ellps=WGS84 +towgs84=0,0,0,-0,-0,-0,0 +no_defs"
LIIE<-"+proj=lcc +lat_1=46.8 +lat_0=46.8 +lon_0=0 +k_0=0.99987742 +x_0=600000 +y_0=2200000 +a=6378249.2 +b=6356515 +towgs84=-168,-60,320,0,0,0,0 +pm=paris +units=m +no_defs"
# Loading the pairs of points
matrix<-read.table(file="file_with_coordinates.csv", header=TRUE, sep=";", stringsAsFactors = F)
The columns of matrix are as follow : origin_id, destination_id, or_lon, or_lat, de_lon, de_lat. Obviously, only the last 4 columns need to be transformed from WGS84 to LIIE.
I'm able to transform the coordinates by doing this :
matrix_sp<-SpatialPoints(coords = od_matrix[,c("de_lon","de_lat","or_lon","or_lat")],proj4string = CRS(WGS84))
matrix_sp_liie<-spTransform(od_matrix_sp, CRSobj = CRS(LIIE))
matrix_liie<-data.frame(matrix_sp_liie)
However, I therefore lose the origin and destination IDs... (And I don't have anything left that could allow me to merge back together matrix_liie with the origin/destination ids in matrix_sp).
I tried this (it's basically the same code but with destination_id and oririgin_id included in the first line), but I couldn't really get to something interesting (I get a Error in .local(obj, ...) : cannot derive coordinates from non-numeric matrix error).
od_matrix_sp<-SpatialPoints(coords = od_matrix[,c("destination_id","oririgin_id","de_lon","de_lat","or_lon","or_lat")],proj4string = CRS(WGS84))
matrix_sp_liie<-spTransform(od_matrix_sp, CRSobj = CRS(LIIE))
matrix_liie<-data.frame(matrix_sp_liie)
Any idea on how I could achieve this ?
Thanks.
Sample from CSV :
origin_id destination_id or_lon or_lat de_lon de_lat
123_a 005 3.88 45.6 1.56 46.7
123_b 006 5.10 41.1 2.4 42.6
Hi it's sp that does the conversion, and you can do that without use SpatialPoints, just specify which columns in matrix are the coordinates with coordinates, here an example :
library("sp")
# Some coordinates
latlong <- data.frame(
ID = 1:8,
LETTERS = LETTERS[1:8],
lon = runif(n = 8, min = 2.0798, max = 2.9931),
lat = runif(n = 8, min = 48.6823, max = 49.0698)
)
# Loading CRS
WGS84<-"+proj=longlat +ellps=WGS84 +towgs84=0,0,0,-0,-0,-0,0 +no_defs"
LIIE<-"+proj=lcc +lat_1=46.8 +lat_0=46.8 +lon_0=0 +k_0=0.99987742 +x_0=600000 +y_0=2200000 +a=6378249.2 +b=6356515 +towgs84=-168,-60,320,0,0,0,0 +pm=paris +units=m +no_defs"
# Set which var are the coord
coordinates(latlong) <- c("lon", "lat")
# Set the proj
proj4string(latlong) <- CRS(WGS84)
# Convert
latlon_conv <- spTransform(x = latlong, CRSobj = CRS(LIIE))
# Back to data.frame
latlon_conv <- as.data.frame(latlon_conv)
latlon_conv # maybe change columns names...
# ID LETTERS lon lat
# 1 1 A 632441.1 2440172
# 2 2 B 633736.7 2434332
# 3 3 C 586298.5 2411320
# 4 4 D 645107.6 2410351
# 5 5 E 642454.6 2443052
# 6 6 F 628371.7 2448833
# 7 7 G 625445.7 2436324
# 8 8 H 624509.7 2443864
EDIT : After seeing #Spacedman comment, you can effectively use SpatialPointsDataFrame instead of SpatialPoints :
latlong.sp <- SpatialPointsDataFrame(
coords = latlong[, c("lon", "lat")],
data = latlong[, c("ID", "LETTERS")],
proj4string = CRS(WGS84)
)
latlon_conv <- spTransform(x = latlong.sp, CRSobj = CRS(LIIE))
latlon_conv.df <- as.data.frame(latlon_conv)
latlon_conv.df

Resources