基于Unable to writeRaster for signature "rasterPCA", "character",我获得了两个栅格,PC1和PC2是一组气候变量。但是,无论具有相同的范围和分辨率,当加载到R时,我的全球环境中的单元格数目不同。错误:nrow(ref)和nrow(target)必须> 0?
下面是我使用的代码,它来自2015年Hamann等人的附录我得到这个错误:
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
我不知道如果这个错误有事情做与差异的数细胞?有什么建议么?
编辑:
基于巴斯蒂安的评论,我调查了结构,我得到这个:
> 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
@Bastien这很有趣。你是对的。目前我正在获得上述内容。将其添加到编辑中。往上看。 –
您是否检查过'l1'和'l2'中的内容? – lbusett