gpt4 book ai didi

r - 找邻居的邻居

转载 作者:行者123 更新时间:2023-12-01 10:18:42 27 4
gpt4 key购买 nike

我有一个 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/

27 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com