R:创建数据帧,每个节点的边缘喜欢同一个对象。

问题描述 投票:0回答:1

我正在创建一个网络,在这个网络中,人们通过他们喜欢的东西被连接起来。我有一个包含人们喜欢的数据框,我想获得一个数据框,在这个数据框中,每个人都与那些喜欢同一对象的人配对。

我所

输入。

object   person
 1        1
 1        2 
 1        3
 2        2
 2        3
 3        3
 4        1
 4        4

我想得到什么

的结果。

person1 person2   object
1       2         1
1       3         1
2       3         1
2       3         2
1       4         4
r dataframe nodes social-networking edges
1个回答
1
投票

这里是一个data.table解决方案

样本数据

library( data.table )
DT <- fread("object   person
1        1
1        2 
1        3
2        2
2        3
3        3
4        1
4        4")

编码

DT[, { #suppress immediate output by using {}
       if( length(person) > 1) {     #combinations only possible for >1 persons
         temp <-  combn( person, 2)  #get all possible 2-person combinations
         list( person1 = temp[1,],   #add combinations to named list
               person2 = temp[2,] )  
         } #end if
     }, #now present the finalt output (i.e. the named list) , 
   by = object ] #for each object

产出

#    object person1 person2
# 1:      1       1       2
# 2:      1       1       3
# 3:      1       2       3
# 4:      2       2       3
# 5:      4       1       4
© www.soinside.com 2019 - 2024. All rights reserved.