Back

Explore Courses Blog Tutorials Interview Questions
0 votes
2 views
in R Programming by (50.2k points)

Basically I am having a dataframe that looks like:

group    x    y

a        1    2

a        3    1

b        1    3

c        1    1

c        2    3

I want to be able to generate all combinations of the x and y columns within a group, like so

group    xy

a        1-2

a        1-1

a        3-2

a        3-1

b        1-3

c        1-1

c        1-3

c        2-1

c        2-3

I've tried using the following code, but it seems as though the group_by function is not working as expected

library(dplyr)

library(tidyr)

combn <- df %>%

group_by(group) %>%

expand(x, y)

My current results are instead giving me every combination of all three columns

head(combn)

group    x    y

a        1    1

a        1    2

a        1    3

a        2    1

a        2    2

a        2    3

Dput:

structure(list(group = structure(c(1L, 1L, 2L, 3L, 3L), .Label = c("a", 

"b", "c"), class = "factor"), x = structure(c(1L, 3L, 1L, 1L, 

2L), .Label = c("1", "2", "3"), class = "factor"), y = structure(c(2L, 

1L, 3L, 1L, 3L), .Label = c("1", "2", "3"), class = "factor")), class = "data.frame", row.names = c(NA, 

-5L))

1 Answer

0 votes
by (108k points)

You can simply use cross_df from purrr to create combinations within a group.

library(dplyr)

df1 <- df %>%

        group_by(group) %>%

        summarise(xy = list(purrr::cross_df(list(a = x, b = y)))) %>%

        tidyr::unnest(xy)

df1

#  group     a     b

#  <fct> <int> <int>

#1 a         1     2

#2 a         3     2

#3 a         1     1

#4 a         3     1

#5 b         1     3

#6 c         1     1

#7 c         2     1

#8 c         1     3

#9 c         2     3

If you want to combine the two columns, you can use unite() also:

tidyr::unite(df1, xy, a, b, sep = "-")

#   group xy   

#  <fct> <chr>

#1 a     1-2  

#2 a     3-2  

#3 a     1-1  

#4 a     3-1  

#5 b     1-3  

#6 c     1-1  

#7 c     2-1  

#8 c     1-3  

#9 c     2-3  

If you are a beginner and want to know about R then do check out the R programming tutorial

Browse Categories

...