Not sure what you are finally trying to achieve but for your first example you could make use of combn
and for examples 2 and 3 you may use expand.grid
to get a data frame of unique combinations of levels of one or more factors:
# Example 1
as.data.frame(t(combn(unique(mtcars$cyl), 2)))
#> V1 V2
#> 1 6 4
#> 2 6 8
#> 3 4 8
# Example 2
expand.grid(cyl = unique(mtcars$cyl), vs = unique(mtcars$vs))
#> cyl vs
#> 1 6 0
#> 2 4 0
#> 3 8 0
#> 4 6 1
#> 5 4 1
#> 6 8 1
# Example 3
expand.grid(cyl = unique(mtcars$cyl), vs = unique(mtcars$vs), am = unique(mtcars$am))
#> cyl vs am
#> 1 6 0 1
#> 2 4 0 1
#> 3 8 0 1
#> 4 6 1 1
#> 5 4 1 1
#> 6 8 1 1
#> 7 6 0 0
#> 8 4 0 0
#> 9 8 0 0
#> 10 6 1 0
#> 11 4 1 0
#> 12 8 1 0
与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…