【问题标题】:Line of best fit with threshold in RR中与阈值的最佳拟合线
【发布时间】:2018-03-04 23:44:26
【问题描述】:

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

使用最低线会更好吗?这对我来说真的是未知的 R 领域,所以我真的不知道如何继续。

【问题讨论】:

标签: r statistics


【解决方案1】:

如果没有示例数据集,很难说什么最适合您,但您可以考虑在 ggplot 中使用 geom_smooth

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

【讨论】:

    猜你喜欢
    • 2016-02-27
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2022-11-23
    • 2014-09-07
    • 2021-12-25
    • 1970-01-01
    • 2022-06-12
    相关资源
    最近更新 更多