【发布时间】:2017-03-17 06:58:51
【问题描述】:
基于Unable to writeRaster for signature "rasterPCA", "character",我得到了一组气候变量的两个栅格,分别是PC1和PC2。但是,无论具有相同的范围和分辨率,当加载到 R 中时,我的全局环境中的单元格数量都会有所不同。
以下是我正在使用的代码,来自 Hamann et al., 2015 的附录,我收到此错误:
library(SDMTools) # install package to read and write ESRI ASCII grids
library(yaImpute) # install package for k-nearest neighbour (kNN) search
lg1 <- asc2dataframe("C:\\Users\\rameshv\\LGM\\4_PCAforR\\PC_1.asc") # principal component grids
lg2 <- asc2dataframe("C:\\Users\\rameshv\\LGM\\4_PCAforR\\PC_2.asc")
present1 <-asc2dataframe("C:\\Users\\rameshv\\Present\\4_PCAforR\\PC_1.asc")
present2 <- asc2dataframe("C:\\Users\\rameshv\\Present\\4_PCAforR\\PC_2.asc")
idxy <- cbind(id=1:nrow(lg1),lg1[,1:2]) # data frame of IDs and XY coords
b <- (max(lg1$var.1)-min(lg1$var.1))/120 # bin size for 120 PC1 bins
l1 <- round(lg1$var.1/b) # convert PC1 to 120 bins via rounding
l2 <- round(lg2$var.1/b) # convert PC2 to <120 bins via rounding
p1 <- round(present1$var.1/b) # same for present PC1
p2 <- round(present2$var.1/b) # same for present PC2
l <- paste(l1,l2) # PC1/PC2 combinations in LGM climate
p <- paste(p1,p2) # PC1/PC2 combinations in present climate
u <- unique(p)[order(unique(p))] # list of unique PC1/PC2 combinations
sid <- c() # empty vector for source IDs
tid <- c() # empty vector for target IDs
d <- c() # empty vector for distances
for(i in u){ # loop for each unique PC1/PC2 combination
lxy <- idxy[which(l==i),] # coordinates of i-th combination in LGM
pxy <- idxy[which(p==i),] # coordinates of i-th combination in present
sid <- c(sid, lxy$id) # append i-th PC1/PC2 combination to previous
if(nrow(pxy)>0){ # kNN search unless no-analogue climate
knn <- data.frame(ann(as.matrix(pxy[,-1]), as.matrix(lxy[,-1]), k=1)$knnIndexDist)
tid <- c(tid, pxy[knn[,1],"id"]) # the IDs of the closest matches
d <- c(d, sqrt(knn[,2])) # their corresponding geographic distances
}
else { # else statement for no-analogue climates
tid <- c(tid, rep(NA,nrow(lxy))) # flag destinations as missing for no analogues
d <- c(d, rep(Inf,nrow(lxy))) # flag distances as infinity for no analogues
}
}
在 for 循环结束时,我收到以下错误:
Error in ann(as.matrix(pxy[, -1]), as.matrix(lxy[, -1]), k = 1) :
error: nrow(ref) and nrow(target) must be > 0
我不确定这个错误是否与单元格数量的差异有关?有什么建议吗?
编辑:
根据 Bastien 的评论,我调查了结构并得到以下信息:
> str(as.matrix(pxy[,-1]))
num [1:27, 1:2] 8.1 8.14 8.22 8.97 9.01 ...
- attr(*, "dimnames")=List of 2
..$ : chr [1:27] "1" "8" "33" "583" ...
..$ : chr [1:2] "y" "x"
> str(as.matrix(lxy[,-1]))
logi[0 , 1:2]
- attr(*, "dimnames")=List of 2
..$ : NULL
..$ : chr [1:2] "y" "x"
建议?
【问题讨论】:
-
错误出现在 yaImpute 的
ann函数中,该函数表示您的 ref 或目标集的大小为 0。运行str(as.matrix(pxy[, -1]))和str(as.matrix(lxy[, -1]))以确保结构正常。您的数据管理可能存在问题 -
@Bastien 这很有趣。你说的对。我目前正在接受上述内容。将其添加到编辑中。见上文。
-
你检查过
l1和l2中的内容吗? -
@LoBu ,是的,我检查了它们。它们都是数字并且有值(它们都不是空的)。
-
查看代码,您的某些
u似乎不存在于l中(无论这些变量是什么)。因此lxy <- idxy[which(l==i),]可能会给出一个“虚假”的结果。