gpt4 book ai didi

r - 如何对 "stepfun"类的两个阶跃函数(R-stepfun)求和?

转载 作者:行者123 更新时间:2023-12-05 01:06:09 24 4
gpt4 key购买 nike

来自示例 here我试图将总和作为“stepfun”类。我想,as.stepfun 是正确的选择,但我的想法行不通。怎么了?

y1 <- c(0, 1, 2, 0)
x1 <- c(1, 2, 3)
f1 <- stepfun(x = x1, y = y1)
print(class(f1))
# [1] "stepfun" "function" # OK!!!
plot(f1)

y2 <- c(0, 1, 0)
x2 <- c(1.5, 2.5)
f2 <- stepfun(x = x2, y = y2)
plot(f2)

fs <- function(x, f1, f2) {
# y <- f1(x) + f2(x) # OK
# y <- as.stepfun(x = x, y = y, ties = "ordered", right = FALSE) # does not work
# return(y) # does not work
return(f1(x) + f2(x))
}
print(class(fs)) # [1] "function"
# attributes(fs) # no new information...

fm <- function(x, f1, f2) {
return(f1(x) * f2(x))
}
print(class(fm)) # [1] "function"

data.frame 的示例 as. 按预期工作:

z <- c(1, 2)
class(z) # [1] "numeric"
class(as.data.frame(z)) # [1] "data.frame"

关于stepfun

的内部结构
function (x, y, f = as.numeric(right), ties = "ordered", right = FALSE) 
{
if (is.unsorted(x))
stop("stepfun: 'x' must be ordered increasingly")
n <- length(x)
if (n < 1)
stop("'x' must have length >= 1")
n1 <- n + 1L
if (length(y) != n1)
stop("'y' must be one longer than 'x'")
rval <- approxfun(x, y[-if (right)
n1
else 1], method = "constant", yleft = y[1L], yright = y[n1],
f = f, ties = ties)
class(rval) <- c("stepfun", class(rval))
attr(rval, "call") <- sys.call()
rval
}

最佳答案

感谢@jblood94、@user2554330 和@rbm here 的回答我找到了一种优雅的方式,我打算在我的案例中使用它。我希望这也对其他人有所帮助:

par(mfrow = c(2, 2))
y1 <- c(0, 1, 2, 0)
x1 <- c(1, 2, 3)
f1 <- stepfun(x = x1, y = y1)

y2 <- c(0, 1, 0)
x2 <- c(1.5, 2.5)
f2 <- stepfun(x = x2, y = y2)

plot(f1)
plot(f2)

'+.stepfun' <- function(f1, f2) {
xs1 <- get("x", envir = environment(f1))
xs2 <- get("x", envir = environment(f2))
xs <- sort(unique(c(x1, x2)))
ys <- f1(c(xs[1] - 1, xs)) + f2(c(xs[1] - 1, xs))
return(stepfun(x = xs, y = ys))
}
f1 + f2
print(class(f1 + f2))
plot(f1 + f2, main = "Sum f1+f2")

'*.stepfun' <- function(f1, f2) {
xs1 <- get("x", envir = environment(f1))
xs2 <- get("x", envir = environment(f2))
xs <- sort(unique(c(x1, x2)))
ys <- f1(c(xs[1] - 1, xs)) * f2(c(xs[1] - 1, xs))
return(stepfun(x = xs, y = ys))
}
f1 * f2
print(class(f1 * f2))
plot(f1 * f2, main = "Sum f1*f2")

par(mfrow = c(1, 1))

关于r - 如何对 "stepfun"类的两个阶跃函数(R-stepfun)求和?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/69738470/

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