LyricalStats9
LyricalStats9

Reputation: 55

Produce all combinations of one element with all other elements within a single column in R

Suppose I have a data frame with a single column that contains letters a, b, c, d, e.

a
b
c
d
e

In R, is it possible to extract a single letter, such as 'a', and produce all possible paired combinations between 'a' and the other letters (with no duplications)? Could the combn command be used in this case?

a b
a c
a d
a e

Upvotes: 2

Views: 152

Answers (3)

Martin Gal
Martin Gal

Reputation: 16978

You could use

expand.grid(x=df[1,], y=df[2:5,])

which returns

  x y
1 a b
2 a c
3 a d
4 a e

Upvotes: 2

TarJae
TarJae

Reputation: 78917

Update: With .before=1 argument the code is shorter :-)

df %>% 
  mutate(col_a = first(col1), .before=1) %>%
  slice(-1)

With dplyr you can:

library(dplyr)
df %>% 
  mutate(col2 = first(col1)) %>%
  slice(-1) %>% 
  select(col2, col1)

Output:

  col2  col1 
  <chr> <chr>
1 a     b    
2 a     c    
3 a     d    
4 a     e  

Upvotes: 2

akrun
akrun

Reputation: 886938

We can use data.frame

data.frame(col1 = 'a', col2 = setdiff(df1$V1, "a"))

-ouptput

col1 col2
1    a    b
2    a    c
3    a    d
4    a    e

data

df1 <- structure(list(V1 = c("a", "b", "c", "d", "e")),
    class = "data.frame", row.names = c(NA, 
-5L))

Upvotes: 3

Related Questions