Reputation: 1101
I have a df listing a number of areas (df$area
) and the areas which these shares a border with (df$next_area
).
Starting from it i want to get a similar df but with the neighbour of its neighbour.
I wrote the following, which works, but appear extremely convoluted.
Was there a better solution?
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))
Upvotes: 3
Views: 83
Reputation: 6796
Here is my approach. I got all area of potential the neighbour of its neighbour and choice the area, not start and neighbour.
df %>%
inner_join(df %>%
rename(next_area = area,
next_next_area = next_area),
by = "next_area") %>%
filter(area != next_next_area) %>%
group_by(area) %>%
filter(! next_next_area %in% next_area) %>%
ungroup()
Upvotes: 1
Reputation: 60080
You could think about this as a graph, and for each node find all the other nodes that are at a distance of 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)
Output:
# 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
Upvotes: 5