Home > database >  R - Getting each combination from a list but in list form
R - Getting each combination from a list but in list form

Time:03-04

I am working on something that requires I get every possible pair combination from a list of characters in a vector and then performing t-tests on the price of each pair.

I figured a good way to start would be to use combn(vector, 2) to get each pair and then iterate through each nested vector to perform a t-test on them. Unfortunately, the output does not produce a vector with nested vectors, and instead just outputs them out in a two-dimensional matrix.

How could I make it so that I have a vector of nested vectors so I can just iterate through each pair of characters instead of each character?

For example, I would want [[A, B], [A, C], [A, D]...] and so on, where subsetting the first item would produce [A, B], subsetting the first item again would produce [A].

But instead, I am getting [A, B, A, C, A, D], where subsetting the first item produces [A], and subsetting the second item produces [B].

CodePudding user response:

I would also use combn as the following:

groups <- LETTERS[1:5]
pair_list <- combn(groups, 2) |> as.data.frame() |> as.list()
pair_list

CodePudding user response:

combn(vector, 2, simplify = F)
  •  Tags:  
  • r
  • Related