I am creating a network where people are connected by what they like. I have a dataframe containing what people like and I want to obtain a dataframe where each person is paired with those how liked the same object
what I have
input:
object person
1 1
1 2
1 3
2 2
2 3
3 3
4 1
4 4
what I want to obtain
result:
person1 person2 object
1 2 1
1 3 1
2 3 1
2 3 2
1 4 4
here is a data.table solution
sample data
library( data.table )
DT <- fread("object person
1 1
1 2
1 3
2 2
2 3
3 3
4 1
4 4")
code
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
output
# object person1 person2
# 1: 1 1 2
# 2: 1 1 3
# 3: 1 2 3
# 4: 2 2 3
# 5: 4 1 4