可扩展的分段功能,适用于任意数量的结/断点

时间:2017-03-16 20:26:59

标签: r

我有以下斜坡,休息和拦截的集合:

slopes <- c(4, 2, 8, 4)
breaks <- c(0.0150, 0.030, 0.035)
intercepts <- c(0.0299, 0.0599, -0.1201, 0.0199)

他们定义以下几行:

# y = slopes[1] * x + intercepts[1]
# y = slopes[2] * x + intercepts[2]
# y = slopes[3] * x + intercepts[3]
# y = slopes[4] * x + intercepts[4]

绘制线条图:

tibble(x = seq(0.0025, 0.06, 0.0025), y = x) %>% 
    ggplot(aes(x, y)) +
    geom_point(alpha = 0) + 
    geom_abline(intercept = intercepts[1], slope = slopes[1], color = "red") + 
    geom_abline(intercept = intercepts[2], slope = slopes[2], color = "orange") + 
    geom_abline(intercept = intercepts[3], slope = slopes[3], color = "yellow") +
    geom_abline(intercept = intercepts[4], slope = slopes[4], color = "green2") +
    scale_y_continuous(limits = c(0, 1))

enter image description here

我想基于线条和断点/节点创建一个分段函数,如下所示(跟随:红色 - &gt;橙色 - &gt;黄色 - &gt;绿色):

enter image description here

我可以在一些if / else语句中包装一个函数来获得我想要的东西。但我希望解决方案可以扩展到任意数量的中断/结(在本例中不是3)。

我怎么能做到这一点?

1 个答案:

答案 0 :(得分:2)

这应该是相当可扩展的:

piecewise <- function(x, slopes, intercepts, breaks) {
    i = 1 + findInterval(x, breaks)
    y = slopes[i] * x + intercepts[i]
    return(y)
}

请注意,我将breaks参数放在最后,因为这对我来说似乎最自然。 它自动为任意数量的片段实现分段定义的函数。

示例:

slopes <- c(4, 2, 8, 4)
intercepts <- c(0.0299, 0.0599, -0.1201, 0.0199)
breaks <- c(0.0150, 0.030, 0.035)

df <- tibble(x = seq(0.0025, 0.06, 0.0025)) %>% 
    mutate(y = piecewise(x, slopes, intercepts, breaks))

df %>% 
    ggplot(aes(x, y)) + 
    geom_line()

enter image description here