Home > Enterprise >  perform the possible combinations two by two in a column in R
perform the possible combinations two by two in a column in R

Time:08-18

I want you to give me all the possible combinations in groups of two by date and place. I have this df

df <- tribble(
  ~date, ~place, ~names, 
  "2022-02-10", "a", "Luis Smith,Johan Devi,Lia Ivanov,Rui Kim",
  "2022-02-11", "b", "Luis Smith,Lia Ivanov,Rui Kim",
  "2022-02-12", "c", "Luis Smith,Johan Devi,Rui Kim", 
)

I have found this code: a<-combn(variables, 2) , the problem is that each of my characters have to be separated and in my column, although they are separated with like, they appear as one:

I expect a result like this:

df<- tribble(
  ~date,    ~place, ~names, ~x1,    ~x2,    ~x3,    ~x4,    ~x5,    ~x6,
  "2022-02-10", "a", "Luis Smith,Johan Devi,Lia Ivanov,Rui Kim",    "Luis Smith,Johan Devi",    "Luis Smith, Lia Ivanov",   "Luis Smith, Rui Kim",  "Johan Devi,Lia Ivanov",    "Johan Devi,Rui Kim",   "Lia Ivanov, Rui Kim",
  "2022-02-11", "b", "Luis Smith,Lia Ivanov,Rui Kim",   "Luis Smith, Lia Ivanov",   "Luis Smith, Rui Kim",  "Lia Ivanov, Rui Kim"   ,   NA,NA,NA,
  "2022-02-12", "c", "Luis Smith,Johan Devi,Rui Kim",   "Luis Smith,Johan Devi",    "Luis Smith, Rui Kim",  "Johan Devi, Rui Kim"   ,   NA,NA,NA,   
)

enter image description here

CodePudding user response:

Here is a way - split the 'names' column at , with strsplit, loop over the list with map, apply the combn , paste the elements and use unnest_wider to create new columns

library(dplyr)
library(tidyr)
library(purrr)
df %>% 
  mutate(x = map(strsplit(names, ","),
    ~ combn(.x, 2, FUN = paste, collapse=", "))) %>%
  unnest_wider(x, names_sep = "")

-output

# A tibble: 3 × 9
  date       place names                                    x1                     x2                     x3                  x4            x5    x6   
  <chr>      <chr> <chr>                                    <chr>                  <chr>                  <chr>               <chr>         <chr> <chr>
1 2022-02-10 a     Luis Smith,Johan Devi,Lia Ivanov,Rui Kim Luis Smith, Johan Devi Luis Smith, Lia Ivanov Luis Smith, Rui Kim Johan Devi, … Joha… Lia …
2 2022-02-11 b     Luis Smith,Lia Ivanov,Rui Kim            Luis Smith, Lia Ivanov Luis Smith, Rui Kim    Lia Ivanov, Rui Kim <NA>          <NA>  <NA> 
3 2022-02-12 c     Luis Smith,Johan Devi,Rui Kim            Luis Smith, Johan Devi Luis Smith, Rui Kim    Johan Devi, Rui Kim <NA>          <NA>  <NA> 
  •  Tags:  
  • r
  • Related