0

I'm running a regression on some data that would benefit from RDD. Thus, I would like to show a Line of Best Fit/Regression Line above and below a threshold of 0.5 on the x-axis. I am struggling to do this. I have tried the clip(x1,x2,y1,y2) command, but it still draws the line across the entire plot. I have also tried to use subsets to draw a regression line >/< 0.5, which also gives a line across the entire plot.

Would it maybe be better to use a lowess line? This is really uncharted R territory for me, so I am really not sure how to proceed.

MGaius
  • 71
  • 2
  • 9
  • could you provide a [reproducible example](https://stackoverflow.com/questions/5963269/how-to-make-a-great-r-reproducible-example)? – missuse Mar 04 '18 at 13:43

1 Answers1

0

without an example data set, it is hard to say what would work best for you, but you could consider geom_smooth within ggplot for that.

library(ggplot2)

# simulated data
set.seed(123)
beta_low <- -3; beta_high <- 2
cut_off <- 0.5 
x = seq(0,1, by = 0.01)
y <- ifelse(x < cut_off, x*beta_low, x*beta_high) + rnorm(length(x),     
                                                    mean = 0, sd = 2)

# add a new variable, say "group", which indicates whether you're before the 
# cut-off or after
df <- data.frame(x, y, group = ifelse(x < cut_off, "before_cut", 
"after_cut"))

# geom_smooth in combination with the group argument in aes() will make sure 
# that lines are only shown for the specified regions >/< 0.5
ggplot(df, aes(x, y, group = group)) +
geom_point() + 
geom_smooth(method = "lm", fill = NA, fullrange = FALSE)

enter image description here

Alternatively, a base R solution:

part1 <- lm(y ~ x, subset=(x<=cut_off))
part2 <- lm(y ~ x, subset=(x>cut_off))
plot(x,y)
segments(min(x), part1$fitted.values[1],                             
         cut_off, rev(part1$fitted.values)[1])
segments(cut_off, part2$fitted.values[1],                             
         max(x), rev(part2$fitted.values)[1])

enter image description here

Daniel
  • 2,207
  • 1
  • 11
  • 15