我在森林中有一個 .ppp 物件。它有兩個標記:灰燼病和物種代碼。灰燼病顯然只影響灰樹;對于其余物種,該列顯示為“NA”。盡管如此,我想提取灰樹的四個最近鄰居,無論是什么物種,然后能夠針對疾病的程度進行繪制。換句話說,要找到灰燼病與不同相鄰物種之間的相關性。
提取了最近的鄰居后,如何將該資料框(或逐列)添加回原始資料框以供以后分析?
library(spatstat)
x <- c(1, 3, 2, 4, 5, 6, 3, 2, 6, 7)
y <- c(3, 4, 5, 2, 2, 6, 7, 8, 4, 3)
ashdis <- c(0.3, 0.95, 0.05, rep(NA, 7))
species <- factor(c("ash", "ash", "ash", "oak", "oak", "beech", "maple", "hickory", "hickory", "beech"))
df <- data.frame(x, y, ashdis, species)
m <- data.frame(ashdis, species)
#convert to .ppp
X <- ppp(df$x, df$y, owin(c(0, 10), c(0, 10)))
marks(X) <- m
plot(X)
#then extract the nearest neighbours of each point in X:
nn <- nnwhich(X, k=1:4)
nn
#trying to add which.1 to data frame as a new column fails:
nn$nn1 <- nn$which.1
#I get this message: "Error in nn$which.1 : $ operator is invalid for atomic vectors"
#alternative way of extracting nearest 4 neighbours also produces error: "Sorry, not implemented when the marks are a data frame"
marktable(X, 4, )
plot(X, pch = 16, cols = "blue", size = 1)
plot(X)
#我應該補充一點,當有單個標記時,上述方法確實有效。但是我可能會失去與其他變數的聯系?
#我也很感激關于如何有意義地將最近鄰列組合成一個可以代表物種組合?灰燼病的組的想法 - 但這不僅僅是一個技術點
uj5u.com熱心網友回復:
您不能只轉換nn為資料框和cbind原始資料嗎?
cbind(df, as.data.frame(nn))
#> x y ashdis species which.1 which.2 which.3 which.4
#> 1 1 3 0.30 ash 2 3 4 5
#> 2 3 4 0.95 ash 3 1 4 5
#> 3 2 5 0.05 ash 2 1 7 8
#> 4 4 2 NA oak 5 2 9 1
#> 5 5 2 NA oak 4 10 9 2
#> 6 6 6 NA beech 9 10 7 2
#> 7 3 7 NA maple 8 3 2 6
#> 8 2 8 NA hickory 7 3 2 6
#> 9 6 4 NA hickory 10 6 5 4
#> 10 7 3 NA beech 9 5 4 6
轉載請註明出處,本文鏈接:https://www.uj5u.com/qianduan/341291.html
