https://postgis.net/docs/ST_MakeLine.html
Would work something like this:
data <- tibble(x1 = 51.4, y1 = 0.45, x2 - 54.23, y2 = 0.67)
line <- data %>%
st_make_line(x1, y1, x2, y2)
Returning a simple feature collection (I think).
Adapting this code would work:
b = graph[, c('from_lon', 'from_lat')]
names(b) = c("long", "lat")
e = graph[, c('to_lon', 'to_lat')]
names(e) = c("long", "lat")
graph$geometry = do.call(
"c",
lapply(seq(nrow(b)), function(i) {
st_sfc(
st_linestring(
as.matrix(
rbind(b[i, ], e[i, ])
)
),
crs = 4326
)
}))
graph = st_as_sf(graph)
You can use R to create LINESTRING from points, e.g.
p1 = st_point(c(51.4, 0.45))
p2 = st_point(c(54.23, 0.67))
st_linestring(rbind(p1, p2))
# LINESTRING (51.4 0.45, 54.23 0.67)
I've seen a few examples along those lines @edzer , but implementing that on a dataframe?
Would it be something like this?
data$geometry <- st_linestring(rbind(
st_point(c(data$from_lon, data$from_lat)),
st_point(data$to_lon, data$to_lat)))
If your data.frame has a single record, yes.
There's also sfheaders which should work on data frames
@JimShady, you can also have a look at https://github.com/etiennebr/geotidy still experimental, but if you need these kind of constructors and don't mind using tibbles, it might work for your needs.
I think I'm missing something obvious.
library(tidyverse)
library(sf)
data <- tibble(x1 = c(1,2,3,4),
y1 = c(1,2,3,4),
x2 = c(1,2,3,4),
y2 = c(1,2,3,4))
data$geometry <- st_linestring(rbind(
st_point(c(data$x1, data$y1)),
st_point(data$x2, data$y2)))
Error in is.numeric(x) && is.matrix(x) :
8 is an illegal number of columns for a POINT
@etiennebr -- Looks very useful ! Thanks, will check it out.
I repeat: if your data.frame has a single record
Thanks, I did read that, but my data does not, so I provided an example of code where there is more than one row of data.
Is there a method to create linestrings for each row? Doesn't seem to be?
st_linestring takes a matrix with points in rows; you'll have to wrangle your data into that form some way.