Home > database >  Create new data frame from nearest neighbour marks in Spatstat
Create new data frame from nearest neighbour marks in Spatstat

Time:10-30

I have a .ppp object of trees in a forest. It has two marks: ash disease and species codes. The ash disease obviously only affects the ash trees; the column reads "NA" for the rest of the species. Nevertheless, I want to extract the four nearest neighbours of the ash trees, whatever species, and be able to then plot against the extent of the disease. In other words, to find a correlation between ash disease and different neighbour species.

Having extracted the nearest neighbours, how do I add that data frame (or column by column) back to the original data frame for later analysis?

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)

#I should add that the above methods DO work when there is a single mark. But then I may lose the connection to the other variables?

#I also would be grateful for ideas on how to meaningfully combine the nearest neighbour columns into a group which can represent a species combo ~ ash disease - but that is more than a technical point

CodePudding user response:

Can't you just convert nn to a data frame and cbind to the original?

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
  • Related