Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
156 views
in Technique[技术] by (71.8m points)

r - How to sort letters in a string?

Let's say I have a string s = "bcabca".

What is the simplest way to get "aabbcc" out of it, i.e., sort the letters in s?

Question&Answers:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Answer

0 votes
by (71.8m points)

Maybe not the most simple answer, but this will work:

paste(sort(unlist(strsplit(s, ""))), collapse = "")

Or modify the strReverse function that is defined in the help page for ?strsplit to suit our needs. We'll call it strSort:

strSort <- function(x)
        sapply(lapply(strsplit(x, NULL), sort), paste, collapse="")

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...