Hi I am trying to sort two values a and b in ascending order and to get a_out and b_out from both of them
a= c("MN, OP, AB")
b = c("MN, O P, A B")
a_out = "AB,MN,OP"
b_out = "A B,MN,O P"
I have tried with the below statement but unable to get desired output
a_out = sort(a)
b_out = sort(b)
Thanks in advance
CodePudding user response:
Split sort and combine the string.
split_and_sort <- function(x) {
toString(sort(unlist(strsplit(x, ',\\s*'))))
}
split_and_sort(a)
#[1] "AB, MN, OP"
split_and_sort(b)
#[1] "A B, MN, O P"
To apply it on column you can use sapply
-
split_and_sort <- function(x) {
sapply(strsplit(x, ',\\s*'), function(x) toString(sort(x)))
}
df$a <- split_and_sort(df$a)
CodePudding user response:
Split the strings and paste them together with strsplit
and unlist
:
> toString(sort(unlist(strsplit(a, ",\\s*"))))
[1] "AB, MN, OP"
>
Or with [[1]]
instead of unlist
:
> toString(sort(strsplit(a, ",\\s*")[[1]]))
[1] "AB, MN, OP"
>