我有一个 df 列出了许多区域( df$area )以及这些区域与( df$next_area )共享边界的区域。
从它开始,我想获得一个类似的 df 但与其邻居的邻居。
我写了以下内容,它有效,但看起来非常复杂。
有没有更好的解决方案?

library(dplyr)
library(tidyr)

df <-     data.frame(area=c("A","A","B","B","C","C","C","D"),next_area=c("B","C","A"    ,"C","A","B","D","C") )
    df <- df %>% group_by(area) %>%
  summarize(next_area = list(sort(unique(as.character(next_area)))))
    df$next_area_exploded <- df$next_area
    for(i in 1:nrow(df)){
      for(j in 1:length(df$next_area[[i]])){
        df$next_area_exploded[[i]][j] <-         list(df$next_area_exploded[[which(df$area==df$next_area[[i]][j])]])
  }
}
df$next_area_exploded <- lapply(df$next_area_exploded, function(x)         unique(unlist(x)))
for(i in 1:nrow(df)){
  df$next_next_area[[i]] <- df$next_area_exploded[[i]]    [!df$next_area_exploded[[i]] %in% df$next_area[[i]]]
  df$next_next_area[[i]] <- df$next_next_area[[i]][!df$next_next_area[[i]]     %in% df$area[[i]]]
  }
df <- df %>% unnest(next_next_area) %>%
  group_by(area) %>%
  mutate(col=paste0(seq_along(area),".add")) %>%
  spread(key=col, value=next_next_area)
df$next_area<-NULL; df$next_area_exploded<-NULL
df_final <- df %>% gather(a,next_next,c(names(df)    [grepl(".add",names(df))])) %>% select(-a) %>% filter(!is.na(next_next))

最佳答案

您可以将其视为一个图形,并为每个节点找到距离为 2 的所有其他节点:

library(igraph)

df <-  data.frame(area=c("A","A","B","B","C","C","C","D"),
                  next_area=c("B","C","A","C","A","B","D","C") )

g = graph_from_data_frame(df)

distances(g) %>%
    as_tibble(rownames = 'area') %>%
    gather(-area, key = 'next_next_area', value = 'distance') %>%
    filter(distance == 2)

输出:
# A tibble: 4 x 3
  area  next_next_area distance
  <chr> <chr>             <dbl>
1 D     A                     2
2 D     B                     2
3 A     D                     2
4 B     D                     2

关于r - 找到邻居的邻居,我们在Stack Overflow上找到一个类似的问题:https://stackoverflow.com/questions/58160651/

10-12 22:16