spatstat中指定window仍报“x,y coords无窗口”错误原因排查
解决spatstat中as.ppp报错"x,y coords given but no window specified"的问题
错误原因
调用as.ppp()时同时传入了包含x/y列的数据框,又额外指定了x和y参数,导致函数参数解析逻辑混乱,无法正确识别window参数。spatstat的as.ppp函数处理数据框输入时,默认会直接读取数据框中的x、y列,无需重复指定这两个参数。
修复步骤
- 修改
as.ppp的调用语句,删除冗余的x和y参数:
cluster1 <- as.ppp(newtotaldf, window = win)
- 额外修正点集质心计算的逻辑错误:原代码使用
centroid.owin(cluster1)会提取窗口的质心,而非当前点集的质心,应改为泛型函数centroid(cluster1)来获取点集的实际质心,确保扩散逻辑符合预期。
修复后的完整代码
library(spatstat) library(dplyr) # 定义窗口 win <- owin(c(0, 100), c(0, 100)) # 生成初始点集群 cluster1 <- rMatClust(kappa = 0.0005, scale = 0.1, mu = 20, win = win, center = c(5,5)) # 定义扩散参数 spread_rate <- 1 new_nests_per_year <- 5 years <- 10 # 绘制初始集群 plot(win, main = "初始集群") points(cluster1, pch = 20, col = "red") # 逐年循环模拟扩散 for (i in 1:years) { # 基于当前点集质心生成新点 current_centroid <- centroid(cluster1) new_y <- rnorm(new_nests_per_year, mean = current_centroid$y, sd = spread_rate) new_x <- rnorm(new_nests_per_year, mean = current_centroid$x, sd = spread_rate) # 转换为数据框并合并 newpoints_df <- data.frame(x = new_x, y = new_y) cluster1_df <- data.frame(cluster1) newtotaldf <- bind_rows(cluster1_df, newpoints_df) # 转换为ppp对象(修复后的调用) cluster1 <- as.ppp(newtotaldf, window = win) # 绘制更新后的集群 plot(win, main = paste("第", i, "年后的集群")) points(cluster1, pch = 20, col = "red") }
内容的提问来源于stack exchange,提问作者OpenSauce
相关产品推荐
相关产品推荐

