[SOLVED] create a column which is a collapsed sorted pair of two existing columns?

Issue

This Content is from Stack Overflow. Question asked by Ishan Mehta

I would like to create a new column which is a sorted version of these 2 columns separated by an underscore (using dplyr mutate method). How is this possible?

> dput(x)
structure(list(sgRNA1_Approved_Symbol = c("ADAD1", "ADAD1", "ADAD1", 
"ADAD1", "ADAD1", "ADAD1", "ADAD1", "ADAD1", "ADAD1", "ADAD1"
), sgRNA2_Approved_Symbol = c("AKT1", "AKT1", "AKT1", "AKT1", 
"BRD4", "BRD4", "BRD4", "BRD4", "MYC", "MYC")), row.names = c(NA, 
-10L), class = c("tbl_df", "tbl", "data.frame"))

This is what I tried:

x %>% 
  mutate(sorted_gene_pair = paste(sort(sgRNA1_Approved_Symbol, sgRNA2_Approved_Symbol), collapse = '_'))



Solution

How about

x %>% 
   mutate(sorted_gene_pair = paste0(
     pmin(x$sgRNA1_Approved_Symbol, x$sgRNA2_Approved_Symbol),
     "_",
     pmax(x$sgRNA1_Approved_Symbol, x$sgRNA2_Approved_Symbol))
   )


This Question was asked in StackOverflow by Ishan Mehta and Answered by Dominik Żabiński It is licensed under the terms of CC BY-SA 2.5. - CC BY-SA 3.0. - CC BY-SA 4.0.

people found this article helpful. What about you?