-1

I am interested in finding out how to convert multiple columns in RStudio into two columns by finding every possible combination excluding null values. Here is sample input:

Mike Bill Pat Ty 
Bob  Bret Mike null
Dyl  Ty   null null

Here is sample output:

Mike Bill
Mike Pat
Mike Ty
Bill Pat
Bill Ty
Pat Ty
Bob Bret
Bob Mike
Bret Mike
Dyl Ty

Any help in solving this would be greatly appreciated. Thanks!

r2evans
  • 141,215
  • 6
  • 77
  • 149
Zach
  • 1

1 Answers1

1

The combn() function combines the elements in all possible ways while maintaining the order.
The t() function transposes the result.
You can put these all together at the end with rbind().

t(combn(c('Mike', 'Bill', 'Pat', 'Ty'), 2))
     [,1]   [,2]  
[1,] "Mike" "Bill"
[2,] "Mike" "Pat" 
[3,] "Mike" "Ty"  
[4,] "Bill" "Pat" 
[5,] "Bill" "Ty"  
[6,] "Pat"  "Ty" 
t(combn(c('Bob', 'Bret', 'Mike', NULL), 2))
     [,1]   [,2]  
[1,] "Bob"  "Bret"
[2,] "Bob"  "Mike"
[3,] "Bret" "Mike"
t(combn(c('Dyl', 'Ty', NULL, NULL), 2))
     [,1]  [,2]
[1,] "Dyl" "Ty"
Brian Montgomery
  • 2,244
  • 5
  • 15