【问题标题】:Create new data frame from nearest neighbour marks in Spatstat从 Spatstat 中的最近邻标记创建新数据框
【发布时间】:2021-12-14 12:56:18
【问题描述】:

我有一个森林中树木的 .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)

#我应该补充一点,当只有一个标记时,上述方法确实有效。但是我可能会失去与其他变量的联系?

#我也很感激关于如何有意义地将最近的邻居列组合成一个可以代表物种组合〜灰病的组的想法 - 但这不仅仅是一个技术点

【问题讨论】:

    标签: r dataframe spatial spatstat


    【解决方案1】:

    您不能将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
    

    【讨论】:

    • 一如既往地@Allan Cameron 有一个优雅简单的解决方案。干杯
    • @DavidCracknell 你是在寻找cbind(df, as.data.frame(apply(nn, 2, function(x) df$species[x]))) 吗?
    猜你喜欢
    • 2012-12-28
    • 2011-08-10
    • 2021-09-19
    • 2014-03-16
    • 2018-05-31
    • 2022-11-30
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多