1

I am trying to sort a contents of a data frame column alphabetically in R, e.g., I have joined two columns

col_1, col_2, col_joined
A, B, A_B,
A, B, A_B,
B, A, B_A,

I would like to have it like:

A, B, A_B,
A, B, A_B,
B, A, A_B,

Not really sure how to do that. Many thanks for your help.

wasif
  • 65
  • 4
  • 12

1 Answers1

0

We can use pmin/pmax to get the rowwise 'min/max' values and paste them together with str_c

library(dplyr)
library(stringr)
df1 %>%
     mutate(col_joined = str_c(pmin(col_1, col_2), pmax(col_1, col_2), sep="_"))
#  col_1 col_2 col_joined
#1     A     B        A_B
#2     A     B        A_B
#3     B     A        A_B

data

df1 <- structure(list(col_1 = c("A", "A", "B"), col_2 = c("B", "B", 
"A")), row.names = c(NA, -3L), class = "data.frame")
akrun
  • 874,273
  • 37
  • 540
  • 662