开发者

How to sort characters in each element of a character vector? [duplicate]

This question already has answers here: Closed 11 years ago.

Possible Duplicate:

How to sort letters in a string i开发者_开发知识库n R?

I have a dataframe where a variable is a character string. Is there a way to create another variable having the same elements as x, but each sorted in ascending or descending order as below:

x_old: (trad, jfwd, qerf...)

x_new: (adrt, dfjw, efqr...)


Using the dummy data:

strs <- c("trad", "jfwd", "qerf")

You can do this with a series of steps over the character vector:

sapply(                                   ## 3
       lapply(                            ## 2
              sapply(strs, strsplit, ""), ## 1
              sort),                      ## 2
       paste, collapse = "")              ## 3

which gives:

> sapply(lapply(sapply(strs, strsplit, ""), sort), paste, collapse = "")
  trad   jfwd   qerf 
"adrt" "dfjw" "efqr"

Where in the function, ## 1 splits each element of the character vector into single characters, ## 2 sorts these sets of characters, and ## 3 pastes them back together again.

We can do this in a single step by encapsulating the steps into a function:

foo <- function(x) {
    x <- strsplit(x, split = "")[[1]]
    x <- sort(x)
    paste(x, collapse = "")
}

which can be used as:

> sapply(strs, foo)
  trad   jfwd   qerf 
"adrt" "dfjw" "efqr"


There must be an easier way:

x <- c("trad", "jfwd", "qerf")
unname(sapply(x, function(i)paste(sort(unlist(strsplit(i, ""))), collapse="")))
[1] "adrt" "dfjw" "efqr"
0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜