[R] how to sort a column with numbers and characters

William Dunlap wdunlap at tibco.com
Sun Jan 11 21:24:08 CET 2015


Change that column to be a factor with the levels in the order that you
wish.
   dataFrame$column <- factor(dataFrame$column, levels=c(1:150, "S", "Z"))
Then it will sort in that order.  E.g.,
  > d <- data.frame(One=c(5,21,10,"Z","S",9), Two=2^(1:6))
  > d[order(d$One),]
    One Two
  3  10   8
  2  21   4
  1   5   2
  6   9  64
  5   S  32
  4   Z  16
  > d$One <- factor(d$One, levels=c(1:150,"S","Z"))
  > d[order(d$One),]
    One Two
  1   5   2
  6   9  64
  3  10   8
  2  21   4
  5   S  32
  4   Z  16


Bill Dunlap
TIBCO Software
wdunlap tibco.com

On Sun, Jan 11, 2015 at 2:21 AM, raz <barvazduck at gmail.com> wrote:

> Hi,
>
> I would like to sort a data frame by a column, the column to sort by has a
> list of numbers 1:150 (a few numbers are missing so the total is 137) and
> two letters "S" , "Z". How can I sort it so that first I have the numbers
> in running order (1,2,3,...150) and then the letters S and Z?
>
> the column class is "factor"
>
>   [1] 1   10  100 101 102 104 105 106 107 108 109 11  110 111 113 114 115
> 116
>  [19] 117 118 119 12  120 122 123 124 125 126 127 128 129 130 131 132 134
> 135
>  [37] 136 137 138 139 140 141 142 143 144 145 146 147 148 149 15  150 16
> 17
>  [55] 18  19  2   20  22  23  24  25  26  27  28  29  3   30  31  32  33
> 34
>  [73] 35  36  37  38  39  4   40  41  42  43  44  45  46  47  48  5   50
> 51
>  [91] 52  53  54  55  56  57  58  59  6   60  61  62  63  64  65  68  69
> 7
> [109] 70  71  72  74  76  77  78  79  8   80  81  82  83  84  85  86  87
> 88
> [127] 89  9   90  91  92  93  94  95  96  97  98  S   Z
>
>
> ​Thanks,
>
> Raz​
>
> --
> \m/
>
>         [[alternative HTML version deleted]]
>
> ______________________________________________
> R-help at r-project.org mailing list -- To UNSUBSCRIBE and more, see
> https://stat.ethz.ch/mailman/listinfo/r-help
> PLEASE do read the posting guide
> http://www.R-project.org/posting-guide.html
> and provide commented, minimal, self-contained, reproducible code.
>

	[[alternative HTML version deleted]]



More information about the R-help mailing list