繁体   English   中英

R中最适合阈值的线

[英]Line of best fit with threshold in R

我正在对一些将从RDD中受益的数据进行回归分析。 因此,我想在x轴上显示一条高于和低于阈值0.5的最佳拟合/回归线。 我正在努力做到这一点。 我已经尝试过clip(x1,x2,y1,y2)命令,但是它仍然在整个图上画线。 我还尝试使用子集绘制> / <0.5的回归线,该回归线还在整个图上给出了一条线。

用最低的线会更好吗? 对我来说,这确实是未知的R领域,所以我真的不确定如何进行。

没有示例数据集中,这是很难说什么工作最适合你,但你可以考虑geom_smoothggplot了点。

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)

在此处输入图片说明

另外, base R解决方案:

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])

在此处输入图片说明

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM