R 集成()函数 returns 'non-finite function value'

R integrate() function returns 'non-finite function value'

我正在尝试对核密度估计 (KDE) 进行 k 折交叉验证,这需要我对平方密度近似值进行积​​分。这是我当前的设置

# Read in crime data from csv file and select only latitude, longitude columns
crimeData <- read.csv("Crimes-Map.csv")
crimeData <- crimeData[, 15:16]
# Remove NAs from the data
cleanData <- crimeData[complete.cases(crimeData), ]
lat <- cleanData[[1]]
lon <- cleanData[[2]]

## Extra code to split my data into k sets ##

hSeq <- seq(0.001, 0.05, by=0.001)
JHLat <- numeric(length(hSeq))
for (i in 1:length(hSeq)) {
  h <- hSeq[i]

  ## Lots of code that's running fine ##

  # Get density estimate for full data to compute J(h)
  latDensity <- density(lat, bw = h)
  latDensFunc <- approxfun(latDensity)
  latSq <- function(x) latDensFunc(x)^2
  # Get support of this density so we integrate over the right region
  loLat <- min(latDensity$x)
  hiLat <- max(latDensity$x)
  JHLat[i] <- integrate(latSq, lower = loLat, upper = hiLat)$value # + other term coming from rest of code
}

集成功能之前一切正常,但出现以下错误:

Error in integrate(lonSq, lower = loLon, upper = hiLon) : non-finite function value

我绘制了 latSq 并使用以下命令检查了密度的支持是否没有无穷大或 NaN

xs <- seq(loLat, hiLat, by = 1e-4)
any(is.infinte(latSq(xs))
any(is.nan(latSq(xs))

两者都 return 错误。作为参考,loLat 为 36.61645,hiLat 为 42.02557。我知道 latDensity 的最大值为 29.979,因此 latSq 的最大值应该为 898.7404,我很确定它的最大值不足以引起问题。所以我对发生了什么以及如何解决它感到非常困惑 - 任何帮助将不胜感激。

您应该检查函数的内插值,而不是积分域。其中一个值必须是 NaN,我无法提供更多信息,因为没有数据。

我只能猜是怎么回事。由于您使用的是 approxfux,其中一个点的插值函数 (latDensFunc) returns NaN。这就是在 lonSq.

中导致 NaNs 的原因