查找两个线性拟合在R中相交的位置 [英] Finding where two linear fits intersect in R

查看:111
本文介绍了查找两个线性拟合在R中相交的位置的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我从R脚本中的lm调用获得了两个线性拟合.例如...

I have two linear fits that I've gotten from lm calls in my R script. For instance...

fit1 <- lm(y1 ~ x1)
fit2 <- lm(y2 ~ x2)

我想找到这两条线(fit1fit2)相交的(x,y)点,如果它们相交的话.

I'd like to find the (x,y) point at which these two lines (fit1 and fit2) intersect, if they intersect at all.

推荐答案

避免几何的一种方法是将方程重新参数化为:

One way to avoid the geometry is to re-parameterize the equations as:

y1 = m1 * (x1 - x0) + y0
y2 = m2 * (x2 - x0) + y0

根据它们的交点(x0, y0),然后使用nls一次执行两者的拟合,以便返回的x0y0值给出结果:

in terms of their intersection point (x0, y0) and then perform the fit of both at once using nls so that the returned values of x0 and y0 give the result:

# test data
set.seed(123)
x1 <- 1:10
y1 <- -5 + x1 + rnorm(10)
x2 <- 1:10
y2 <- 5 - x1 + rnorm(10)
g <- rep(1:2, each = 10) # first 10 are from x1,y1 and second 10 are from x2,y2

xx <- c(x1, x2)
yy <- c(y1, y2)
nls(yy ~ ifelse(g == 1, m1 * (xx - x0) + y0, m2 * (xx - x0) + y0),
    start = c(m1 = -1, m2 = 1, y0 = 0, x0 = 0))

请注意,行xx<-...yy<-...是新行,并且已经根据这些行指定了nls行并对其进行了纠正.

Note that the lines xx<-... and yy<-... are new and the nls line has been specified in terms of those and corrected.

这篇关于查找两个线性拟合在R中相交的位置的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆