我正在处理的数据帧以二元格式编码,其中每个观察(即行)包含一个源节点(from
)和一个目标节点(to
)以及其他一些二元协变量(例如二元相关性corr
)。
为简单起见,我想将每个 dyad 视为无序并为每个 dyad 生成一个唯一标识符,如下面的(即df1
):
# original data
df <- data.frame(
from = c("A", "A", "A", "B", "C", "A", "D", "E", "F", "B"),
to = c("B", "C", "D", "C", "B", "B", "A", "A", "A", "A"),
corr = c(0.5, 0.7, 0.2, 0.15, 0.15, 0.5, 0.2, 0.45, 0.54, 0.5))
from to corr
1 A B 0.50
2 A C 0.70
3 A D 0.20
4 B C 0.15
5 C B 0.15
6 A B 0.50
7 D A 0.20
8 E A 0.45
9 F A 0.54
10 B A 0.50
# desired format
df1 <- data.frame(
from = c("A", "A", "A", "B", "C", "A", "D", "E", "F", "B"),
to = c("B", "C", "D", "C", "B", "B", "A", "A", "A", "A"),
corr = c(0.5, 0.7, 0.2, 0.15, 0.15, 0.5, 0.2, 0.45, 0.54, 0.5),
dyad = c(1, 2, 3, 4, 4, 1, 3, 5, 6, 1))
from to corr dyad
1 A B 0.50 1
2 A C 0.70 2
3 A D 0.20 3
4 B C 0.15 4
5 C B 0.15 4
6 A B 0.50 1
7 D A 0.20 3
8 E A 0.45 5
9 F A 0.54 6
10 B A 0.50 1
其中 dyad AB/BA、AD/DA 被视为相同的对,并分配有相同的 dyad 标识符。虽然从原始数据中提取无序对的列表很容易,但很难将它们映射到原始数据帧以生成无序的二元标识符。有人可以对此提供一些见解吗?