[英]R Tidyverse expand a dataframe with all combinations of two variables (edgelist)
[英]Create edgelist of all possible combinations
我有一個數據框,其中包含人員列表以及他們在哪里工作的相應緯度坐標。 本質上,我想創建一個新的數據框,以表示一個邊緣列表,該邊緣列表顯示每個人與原始數據框中的所有其他人之間的距離。 我知道如何計算距離,但是在for循環中苦苦掙扎。
原始數據幀如下所示(坐標=元組):
name, coord
Bob -30, 142
Jack 32, 3
Alfred 40, - 116
我需要生成這樣的新數據框:
from, to, from_coord, to_coord
Bob, Bob, -30, 142, -30, 142
Bob, Jack, -30, 142, 32, 3
Bob, Alfred, -30, 142, 40, -116
Jack, Jack 32, 3, 32, 3
Jack, Alfred 32, 3, 40, -116
Alfred, Alfred 40, -116, 40, -116
排序后,我可以輕松計算距離。
我嘗試使用兩個嵌套的for循環來創建它,但是卻塞滿了我的cbind,rbinds。
這是使用setNames
和with
,然后使用expand.grid
的基本解決方案
x <- with(df, setNames(name, coord))
x1 <- cbind(expand.grid(x,x),expand.grid(names(x),names(x)))
colnames(x1)<-c("from","to","from_coord","to_coord")
from to from_coord to_coord
1 Bob Bob -30, 142 -30, 142
2 Jack Bob 32, 3 -30, 142
3 Alfred Bob 40, -116 -30, 142
4 Bob Jack -30, 142 32, 3
5 Jack Jack 32, 3 32, 3
6 Alfred Jack 40, -116 32, 3
7 Bob Alfred -30, 142 40, -116
8 Jack Alfred 32, 3 40, -116
9 Alfred Alfred 40, -116 40, -116
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.