如果我有条件公式,那么:
时间<theta:y = x ^ 2
time => theta:y = x
我如何使用R中的as.formula函数来构建类似的东西?(我也需要在它上面使用nls函数).
我试过了:
Data2 <-as.formula(y ~ (x<=theta)*x^2 + (x>theta)*x)
Run Code Online (Sandbox Code Playgroud)
但它不起作用.
我不认为你可以使用nls适合不可区分的功能.
您可以使用optimize此特定示例:
#some example data
set.seed(42)
x <- runif(100, 0, 100)
y <- x
y[x <= 50] <- x[x <= 50]^2
y <- y + rnorm(100, sd = 0.01)
fun <- function(x, theta) {
#logical values are coerced to 0/1 automatically in calculations
x * (x > theta) + x^2 * (x <= theta)
}
SSE <- function(theta) {
sum((y - fun(x, theta))^2)
}
print(fit <- optimize(SSE, c(0, 100)))
#$minimum
#[1] 48.40996
#
#$objective
#[1] 0.008573424
plot(x, y)
lines(0:100, fun(0:100, fit$minimum))
Run Code Online (Sandbox Code Playgroud)