Skip to content
Prev 27075 / 29559 Next

Sampling random directional lines within a polygon

Hi everyone,

I wanted to generate random lines between two spatial points (random points
in polygons). The lines should consist of segments (9 segments), after
following suggestions I received to my previous post, I ended up using
trajectories. My aim now is to restrict these random trajectories (see
points in the attachment as an example) to the extent of a polygon (shown
in the attachment in yellow). So the trajectories should lie within the
polygon.
Please find the code I used below:
I first generated a data frame with my start and end point and used it to
generate a trajectory (straight line in attachment). I then generated a
random trajectory and shifted it so that the start and endpoints were equal
to my first trajectory. I transformed the matrices to a Spatial Data frame
to be able to plot it. Does anyone know how I can restrict the extent of
the trajectory that I randomly generate?

#coordinates of start and end point and time steps
x<-c(1649786,-1636500)
y<-c(-2902593,738500)
times<-c(0,9)
start_end_points<-as.data.frame(cbind(x,y,times))

# generate a trajectory between start and endpoint
trj<-TrajFromCoords(point_trj,xCol=1,yCol=2,timeCol=3, spatialUnits="m",
timeUnits="d")

# generate a random trajectory with 9 segments
track<-TrajGenerate(n=9, random=T, stepLength=TrajLength(trj)/9)

# To be able to use StartEndTranslate transform trajectories into matrices
ma1<-as.matrix(trj)
ma2<-as.matrix(track)

# Translate, rotate and scale the points of traj2 using traj1. The new traj
will have the same start and end points as traj1.
p<-StartEndTranslate(ma1,ma2)

# to check if this worked transform into SpatialDataFrame
# the start and end point of the new matrix are the same as the traj1 which
is good, the rest of the points changed as well
p_df<-as.data.frame(p)

# change lat / longs to nummeric
p_df$x<-as.numeric(p_df$x)
p_df$y<-as.numeric(p_df$y)

# generate a spatial dataframe to check if the StartEndTranslate function
worked by plotting it
xy<-p_df[,c(1,2)]

spdf<-SpatialPointsDataFrame(coords=xy, data=p_df, proj4string =
CRS(projection))

Thank you very much!

On Wed, Feb 6, 2019 at 5:42 PM Barry Rowlingson <b.rowlingson at gmail.com>
wrote:
-------------- next part --------------
An HTML attachment was scrubbed...
URL: <https://stat.ethz.ch/pipermail/r-sig-geo/attachments/20190212/61f58f91/attachment.html>

-------------- next part --------------
A non-text attachment was scrubbed...
Name: restrict_trajectory_to_extent_of_polygon2.jpg
Type: image/jpeg
Size: 14874 bytes
Desc: not available
URL: <https://stat.ethz.ch/pipermail/r-sig-geo/attachments/20190212/61f58f91/attachment.jpg>