5

Is there any way to create lines in R connecting two points? I am aware of lines(), function, but it creates line segment what I am looking for is an infinite length line.

Udayan Maurya
  • 75
  • 1
  • 1
  • 5
  • 3
    Maybe `abline`? https://stat.ethz.ch/R-manual/R-devel/library/graphics/html/abline.html – Marta Jan 07 '16 at 14:56
  • Thanks for the reply, but I was not looking for abline. I like to move parametrically in vector space rather than a coordinate geometry (y=mx+c) solution. – Udayan Maurya Jan 08 '16 at 16:11

3 Answers3

6

Here's an example of Martha's suggestion:

set.seed(1)
x <- runif(2)
y <- runif(2)

# function
segmentInf <- function(xs, ys){
  fit <- lm(ys~xs)
  abline(fit)
}

plot(x,y)
segmentInf(x,y)

enter image description here

Marc in the box
  • 11,769
  • 4
  • 47
  • 97
3
#define x and y values for the two points
x <- rnorm(2)
y <- rnorm(2)
slope <- diff(y)/diff(x)
intercept <- y[1]-slope*x[1]
plot(x, y)
abline(intercept, slope, col="red")
# repeat the above as many times as you like to satisfy yourself
doctorG
  • 1,681
  • 1
  • 11
  • 27
1

Use segment() function.

#example    
x1 <- stats::runif(5)
x2 <- stats::runif(5)+2
y <- stats::rnorm(10)


plot(c(x1,x2), y)


segments(x1, y[1:5], x2, y[6:10], col= 'blue')