Learn R Programming

wrMisc (version 2.1.0)

vectorDistAngle: Vector Distance and Angle

Description

Compute the Euclidean distance and angle (in radians) for 2-dimensional vectors defined by start and end points in the first and second columns of argumnents x and y.

Usage

vectorDistAngle(
  x,
  y,
  addCoord = FALSE,
  silent = FALSE,
  debug = FALSE,
  callFrom = NULL
)

Value

This function returns a data.frame with the columns:

`dist`

Numeric vector of Euclidean distances

`angle`

Numeric vector of angles in radians

Optionally the original start and end-coordinates to output may get added if addCoord=TRUE

Arguments

x

(numeric matrix or data.frame of 2 column, min 2 rows) describes start & end x-coordinates

y

(numeric matrix or data.frame of 2 column, min 2 rows) describes start & end x-coordinates

addCoord

(logical) add original start and end-coordinates to output

silent

(logical) suppress messages

debug

(logical) display additional messages for debugging

callFrom

(character) allow easier tracking of messages produced).

Details

The input x and y is considered as describing start- and enc-points of vectors in two-dim space. Each row of x describes the starting and end-points of separate (and independent) vectors along the x- and y-axis.

Then, the function calculates for each line the **distance** as Euclidean distance and the **angle** as atan2(y_diff, x_diff)` in radians (range: `[-pi, pi]`), measured counterclockwise from the positive x-axis.

This function was designed for movement trajectories or any paired coordinate data where direction and magnitude matter. If x and y contain more than 2 columns, these additional columns will be ignored.

See Also

Examples

Run this code
x <- matrix(c(0, 3, 0.5, 4, 1, 1), ncol=2, byrow=TRUE)  # x: (0,0)→(3,0), (0,0)→(4,0), (0,0)→(0,0)
y <- matrix(c(0, 0, 1, 3, 0.5, 5), ncol=2, byrow=TRUE)  # y: (0,0)→(0,0), (0,0)→(3,0), (0,0)→(5,0)
(vectDist <- vectorDistAngle(x, y))

plot(cbind(x=as.numeric(x),y=as.numeric(y)), main="Example for vectorDistAngle()",las=1)
arrows(x[,1],y[,1],x[,2],y[,2])
text(x[,2], 0.1 +y[,2], paste0("dist=",round(vectDist[,1],2),
  ", angle=",round(vectDist[,2],2)), adj=1)

Run the code above in your browser using DataLab