[R] how to order each element according to alphabet

David Winsemius dwinsemius at comcast.net
Fri Jul 15 13:27:37 CEST 2011


On Jul 15, 2011, at 12:23 AM, onthetopo wrote:

>> dd
>     [,1] [,2]
> [1,] "OP" "SU"
> [2,] "XA" "YQ"
>
> sapply( lapply(
> + strsplit(dd, split=""), sort),
> + paste, collapse="")
>
> [1] "OP" "AX" "SU" "QY"
>
> The result is not what I intended since it is a single line.
> It should be:
>     [,1] [,2]
> [1,] "OP" "SU"
> [2,] "AX" "QY"

  sortvec <- function(x)
    paste(
        sapply( strsplit(x, split=""), sort),
        sep="")

  apply(dd, 1:2, sortvec)
      [,1] [,2]
[1,] "OP" "SU"
[2,] "AX" "QY"

-- 

David Winsemius, MD
West Hartford, CT



More information about the R-help mailing list