gpt4 book ai didi

r - 适用于任意数量的结/断点的可扩展分段函数

转载 作者:行者123 更新时间:2023-12-01 07:57:49 24 4
gpt4 key购买 nike

我有以下斜率、转折点和截距的集合:

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

我想创建一个基于线和断点/结点的分段函数,如下所示(遵循:红色 -> 橙色 -> 黄色 -> 绿色):

enter image description here

我可以将一个函数包装在几个 if/else 语句上以获得我想要的。但我希望该解决方案可以针对任意数量的断裂/结进行扩展(在此示例中,而不是仅仅 3 个)。

我怎样才能做到这一点?

最佳答案

这应该是相当可扩展的:

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

关于r - 适用于任意数量的结/断点的可扩展分段函数,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/42844162/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com