r-在给定有向矢量的情况下计算XY坐标



我有这些数据:

set.seed(1)
df <- data.frame(xstart=rnorm(5),ystart=rnorm(5),
xmax=rnorm(5),ymax=rnorm(5),
length=runif(5,0,1))

其中,xstartystart定义向量(即,该2D空间中具有方向的线(的起始坐标,length定义其长度。xmaxymax定义了矢量的方向(即(ymax - ystart)/(xmax - xstart)是斜率(。

我正在寻找一个函数来计算每个向量的xend和yend坐标。本质上,这可以使用以下方程来解决:

length^2 = (xend - xstart)^2 + (yend - ystart)^2
yend = beta*(xend - xstart)

其中:

beta = (ymax - ystart)/(xmax - xstart)

这是纯几何体。我建议使用atan2来代替斜率,因为它是有限定义的(反之亦然,Inf-Inf的斜率带有垂直线(。

angles <- atan2(df$ymax - df$ystart, df$xmax - df$xstart)
df$xend <- df$xstart + df$length * cos(angles)
df$yend <- df$ystart + df$length * sin(angles)
# and to verify the resulting lengths are as-desired
df$len2 <- sqrt( (df$xend - df$xstart)^2 + (df$yend - df$ystart)^2 )
df
#       xstart     ystart       xmax        ymax    length       xend        yend      len2
# 1 -0.6264538 -0.8204684  1.5117812 -0.04493361 0.8209463  0.1452983 -0.54055500 0.8209463
# 2  0.1836433  0.4874291  0.3898432 -0.01619026 0.6470602  0.4288186 -0.11138308 0.6470602
# 3 -0.8356286  0.7383247 -0.6212406  0.94383621 0.7829328 -0.2704346  1.28011746 0.7829328
# 4  1.5952808  0.5757814 -2.2146999  0.82122120 0.5530363  1.0433885  0.61133438 0.5530363
# 5  0.3295078 -0.3053884  1.1249309  0.59390132 0.5297196  0.6804608  0.09139217 0.5297196

因此,作为一个函数,类似于:

somefunc <- function(xstart, ystart, xmax, ymax, len) {
angles <- atan2(ymax - ystart, xmax - xstart)
xend <- xstart + len * cos(angles)
yend <- ystart + len * sin(angles)
data.frame(xend = xend, yend = yend)
}

其返回具有两个期望列的帧。使用cbind(origdat, somefunc(...))可以很容易地将它们添加到现有数据中。

相关内容

最新更新