2

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

3 Answers3

3

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))

akrun
  • 874,273
  • 37
  • 540
  • 662
2

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  
TarJae
  • 72,363
  • 6
  • 19
  • 66
2

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
Martin Gal
  • 16,640
  • 5
  • 21
  • 39