R language study notes - number of combinations

Number of combinations: The number of all combinations of n (n≤m) elements taken from m different elements is called the number of combinations of n elements taken from m different elements.

Code:

str_comb <- function(vector){
  n <- length(vector)
  num=0 #Keep the number of all combinations
  col=1 #Used for loop stacking
  for (i in 1:n) {
    num=num+choose(n,i)
  } #Calculate the number of combinations
  comb_matrix <- matrix(,nrow = num,ncol = 1) #Save the combined result with a matrix
  for (j in 1:n) {
    comb_res <- combn(vector,j) # generate a combination of length j
    m <- ncol(comb_res) #Calculate the number of columns where the combination is located, that is, the number of combinations
    for (l in 1:m) {
      comb_matrix[col,1] <- paste(comb_res[,l],collapse = ',')#Character combination function
      col = col + 1
      if(col==num)break#When the number of combinations reaches the final number, jump out of the loop
    }
  }
  return(comb_matrix)
}
a <- c('A','B','C','D')
str_comb(a)

operation result:

> str_comb(a)
      [,1]     
 [1,] "A"      
 [2,] "B"      
 [3,] "C"      
 [4,] "D"      
 [5,] "A,B"    
 [6,] "A,C"    
 [7,] "A,D"    
 [8,] "B,C"    
 [9,] "B,D"    
[10,] "C,D"    
[11,] "A,B,C"  
[12,] "A,B,D"  
[13,] "A,C,D"  
[14,] "B,C,D"  
[15,] "A,B,C,D"

Guess you like

Origin http://43.154.161.224:23101/article/api/json?id=325074833&siteId=291194637