I have a dataframe with two sets of coordinates X,Y and prevXal,prevYval and I would like to make linestrings column wise, and create an sf object of the same number of linestrings as rows in the dataframe.
Using this dataframe example, I would like to create 4 linestrings.
library(sf)
df
X Y prevXval prevYval
1 -0.121 65.001 0.067 65.117
2 180.000 -50.039 -179.879 -50.156
3 -0.075 47.787 0.038 47.904
4 179.754 -73.960 -179.900 -73.979
I started with st_linestring()
, but this function works down the rows.
So I tried a function to break up the points to the right input format for st_linestring()
.
# Create a function that creates a linestring - that extracts vectors (using the as.numeric fn) of the X,Y and prevXval, prevYval points from nx4 dataframe, then bind to a matrix
make_line <- function(x) {rbind(as.numeric(df[x,1:2]),
as.numeric(df[x,3:4]))%>%
# Convert to a linestring object
st_linestring()
make_line(1)
LINESTRING (-0.121 65.001, 0.067 65.117)
This works for one row, but I can't seem to find an efficient way to iterate over all the rows, having also tried purrr. Any suggestions?