有人知道如何解决这个 R 问题吗?它是在关系中找到一个变化点,比如下面数据中的 x=5。
fitDat <- data.frame(x=1:10, y=c(rnorm(5, sd=0.2),(1:5)+rnorm(5, sd=0.2)))
plot(fitDat$x, fitDat$y)
SAS 运行良好;
/*simulated example*/
data test;
INPUT id $ x y;
cards;
1 1 -0.22711769
2 2 -0.08712909
3 3 0.06922072
4 4 -0.12940913
5 5 -0.43152927
6 6 1.17685016
7 7 1.83410448
8 8 2.88528795
9 9 4.30078012
10 10 4.84517101
;
run;
proc nlmixed data=test;
parms B0 = 0 B1=1 t0=5 sigma_r=1;
mu1 = (x <= t0)*B0;
mu2 = (x > t0)*(B0 + B1*(x - t0));
mu=mu1+mu2;
model y~normal(mu,sigma_r);
run;
R失败;
changePointOptim <- function(x, int, slope, delta){ # code adapted from https://stats.stackexchange.com/questions/7527/change-point-analysis-using-rs-nls
int + (pmax(delta-x, 0) * slope)
}
# nls
nls(y ~ changePointOptim(x, b0, b1, delta),
data = fitDat,
start = c(b0 = 0, b1 = 1, delta = 5))
# optimization
sqerror <- function (par, x, y)
sum((y - changePointOptim(x, par[1], par[2], par[3]))^2)
minObj <- optim(par = c(0, 1, 3), fn = sqerror,
x = fitDat$x, y = fitDat$y, method = "BFGS")
minObj$par
# nlme
library(nlme)
nlmeChgpt <- nlme(y ~ changePointOptim(b0, b1, delta,x),
data = fitDat,
fixed = b0 + b1 + delta,
start = c(b0=0, b1=1, delta=5))
summary(nlmeChgpt)
由于这是一个信号清晰的简单案例,因此 R 应该可以工作。我想知道我在 R 中做错了什么(我使用了来自https://stats.stackexchange.com/questions/7527/change-point-analysis-using-rs-nls的一些代码)。有人建议/解决方案吗?
谢谢!
威廉