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.
Asked
Active
Viewed 1.6k times
5
-
3Maybe `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 Answers
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)

Marc in the box
- 11,769
- 4
- 47
- 97
-
1Thanks, I believe creating a self-defined function like this is the best solution. Probably R does not have any such predefined function. – Udayan Maurya Jan 08 '16 at 16:13
-
I have up voted but my level is 11 right now. Once I reach 15 the vote will be applicable. – Udayan Maurya Jan 18 '16 at 10:17
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')