Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
791 views
in Technique[技术] by (71.8m points)

statistics - How do you find all possible unique pairwise comparisons of variables with various levels (with 3 example scenarios) using R for the mtcars data?


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Answer

0 votes
by (71.8m points)

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

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...