Reputation: 45
I have tried a lot of things and I even searched for similar questions but couldn't find solutions.
Suppose that we have a data.table in R:
ID = c("1","1","1","2","2")
Code = c("A","B","C","B","C")
N = c("3","3","3","2","2")
so basically, I want to have unique pairwise combinations for column "Code" based on "ID" and "N" columns.
Is there an R function to return the following?
ID = c("1","1","1","2")
Combinations = c("A.B","B.C","C.A","B.C")
N = c("3","3","3","2")
as I said before I have tried many things but if gives me a data.table which contains only the combinations however in my final result I need to have a column for ID and 2 others for combinations and N
Do you have an idea how to do it ?
Upvotes: 0
Views: 652
Reputation: 388817
You may use combn
in group_by
-
library(dplyr)
result <- df %>%
group_by(ID, N) %>%
summarise(Code = combn(Code, 2, paste0, collapse = '.'), .groups = 'drop')
result
# ID N Code
# <chr> <chr> <chr>
#1 1 3 A.B
#2 1 3 A.C
#3 1 3 B.C
#4 2 2 B.C
data
df <- data.frame(ID, Code, N)
Upvotes: 1