Finding pairs in a table in R -


i need identfy pairs of numbers in table in r. structure of table follows:

   user_a   user_b   counter 1       1        2         5 2       1        3         3 3       2        1        10 4       2        4         8 

i want check if each pair, opposite 1 exists, e.g. pair (1,2) , pair (2,1), , if - sum counter value both pairs. result, want have output in form of table one:

   user_a   user_b   sum   bi_directional 1       1        2    15             true 2       1        3     3            false 3       2        4     8            false 

thank in advance!

we can sort first 2 column row wise apply (margin=1), cbind third column ('d1'), index of duplicates of first 2 column ('i1'). convert 'data.table' (setdt(d2)), grouped 'user_a', , 'user_b', sum of 'counter' , first row of 'i1'.

 d1 <- setnames(cbind(t(apply(df[1:2], 1, sort)), df[3]), names(df))   i1 <- duplicated(d1[1:2])|duplicated(d1[1:2], fromlast=true)   d2 <- cbind(d1, i1)  library(data.table)  setdt(d2)[, list(counter=sum(counter), bi_directional=i1[1l]) ,.(user_a, user_b)]  #  user_a user_b counter bi_directional  #1:      1      2      15           true  #2:      1      3       3          false  #3:      2      4       8          false 

or option is

setdt(df)[user_a > user_b, c('user_b', 'user_a') :=         list(user_a, user_b)] df[, list(counter= sum(counter), bi_directional= .n>1),                                     = .(user_a, user_b)] #     user_a user_b counter bi_directional #1:      1      2      15           true #2:      1      3       3          false #3:      2      4       8          false 

Comments

Popular posts from this blog

javascript - jQuery: Add class depending on URL in the best way -

caching - How to check if a url path exists in the service worker cache -

Redirect to a HTTPS version using .htaccess -