I have the following data frame :
# A tibble: 3 x 4
index number_1 number_2 number_3
<int> <chr> <chr> <chr>
1 1 32 16 29
2 2 13 50 47
3 3 37 19 18
I would like to run a combn
function with an parameter of 2 to every line of that tibble between the 3 columns number
; that would yield a result along the lines of :
# A tibble: 3 x 2
index combn
<dbl> <chr>
1 1 32,16
2 1 32,29
3 1 16,29
4 2 13,50
.............
I have thought of something like
theTibble %>%
(
select(., number_1 : nulber_3) %>% lapply(FUN = combn,2)
) %>% View
but to no avail.
I would like a pipe friendly solution. What a possible solution would be?
Thank you for your help
You can get the data in long format, for each index
apply combn
function selecting 2 values at a time, paste them into comma-separated string (toString
) and unnest
.
library(dplyr)
library(tidyr)
df %>%
pivot_longer(cols = -index) %>%
group_by(index) %>%
summarise(combn = list(combn(value, 2, toString))) %>%
unnest(combn)
# index combn
# <int> <chr>
#1 1 32, 16
#2 1 32, 29
#3 1 16, 29
#4 2 13, 50
#5 2 13, 47
#6 2 50, 47
#7 3 37, 19
#8 3 37, 18
#9 3 19, 18