Reputation: 55
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
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
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
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
df1 <- structure(list(V1 = c("a", "b", "c", "d", "e")),
class = "data.frame", row.names = c(NA,
-5L))
Upvotes: 3