R中的拟合棚车(矩形)功能

Fitting boxcar (rectangle) function in R

我正在尝试将 boxcar / rectangle 函数拟合到 R 中的数据集。我正在使用 nls 和一个自定义函数来描述不同宽度的单位脉冲。这是我目前所拥有的:

# Defines the unit pulse function
# The left side of the pulse is at x0, the right at x1
pulse <- function(x, x0, x1) {
  if (x >= x0 & x <= x1) {
    return (1)
  } else {
    return (0)
  }
}

xdata <- 1:30
ydata <- c(sample(-1:1, 10, replace = TRUE), sample(10:15, 10, replace = TRUE), sample(-1:1, 10, replace = TRUE))

plot(xdata, ydata)

df <- data.frame(xdata, ydata)

fitfit <- nls(ydata ~ I(A * pulse(xdata, L, R) + B), df, start = list(L = 0, R = 1, B = 0, A = 10))

我无法理解我收到的错误:

Error in qr(.swts * attr(rhs, "gradient")) : dims [product 4] do not match the length of object [30] In addition: Warning messages: 1: In if (x >= x0 & x <= x1) { : the condition has length > 1 and only the first element will be used 2: In if (x >= x0 & x <= x1) { : the condition has length > 1 and only the first element will be used 3: In if (x >= x0 & x <= x1) { : the condition has length > 1 and only the first element will be used 4: In if (x >= x0 & x <= x1) { : the condition has length > 1 and only the first element will be used 5: In if (x >= x0 & x <= x1) { : the condition has length > 1 and only the first element will be used 6: In if (x >= x0 & x <= x1) { : the condition has length > 1 and only the first element will be used 7: In .swts * attr(rhs, "gradient") : longer object length is not a multiple of shorter object length

你的脉冲函数 return 不是向量,试试这个:

pulse <- function(x, x0, x1) {
     ifelse (x >= x0 & x <= x1,1,0)
}

非平滑函数可能会导致问题。尝试在脉冲的两个边界上使用蛮力,并在线性参数上进行优化。请注意,下面我们添加了一个 set.seed 以使 ydata 可重现。

library(nls2)

set.seed(123)
xdata <- 1:30
ydata <- c(sample(-1:1, 10, replace = TRUE), sample(10:15, 10, replace = TRUE), 
  sample(-1:1, 10, replace = TRUE))
df <- data.frame(xdata, ydata)

pulse <- function(x, x0, x1) (x >= x0 & x <= x1) + 0
st <- subset(expand.grid(L = xdata, R = xdata), L < R)

nls2(ydata ~ cbind(pulse(xdata, L, R), 1), df, start = st, alg = "plinear-brute")

给出了一些您可以忽略的错误消息,最后是这个输出,其中 .lin1.lin2 对应于问题中的 AB

Nonlinear regression model
  model: ydata ~ cbind(pulse(xdata, L, R), 1)
   data: df
    L     R .lin1 .lin2 
 11.0  20.0  12.4   0.2 
 residual sum-of-squares: 49.6

Number of iterations to convergence: 435 
Achieved convergence tolerance: NA