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.

2

3 Answers 3

7

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

2
  • 1
    Thanks, I believe creating a self-defined function like this is the best solution. Probably R does not have any such predefined function. Jan 8, 2016 at 16:13
  • I have up voted but my level is 11 right now. Once I reach 15 the vote will be applicable. Jan 18, 2016 at 10:17
4
#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
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')
2
  • Thanks, but i was not looking for segments. Jan 8, 2016 at 16:14
  • why you dont want segments ?
    – user5511175
    Jan 8, 2016 at 20:15

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Not the answer you're looking for? Browse other questions tagged or ask your own question.