[R] How to remove levels?

David Winsemius dwinsemius at comcast.net
Thu Mar 18 02:13:06 CET 2010


On Mar 17, 2010, at 8:57 PM, Soyeon Kim wrote:

> Dear All,
>
> My data looks like this
>> new_ns
>   chr nc_two nc_not_two
> 1    1    488         58
> 2    2    325        114
> 3    3    233         79
> 4    4    200        153
> 5    5    239         53
> 6    6    196        313
> 7    7    229         45
> 8    8    231        137
> 9    9    164        111
> 10  10    156         45
> 11  11    181         92
> 12  12    179         52
> 13  13     72         30
> 14  14     73         62
> 15  15    185         25
> 16  16     93         42
> 17  17     84         50
> 18  18     33         17
> 19  19     31         40
> 20  20     49          8
> 21  21     12         16
> 22  22     26         37
>
>> new_ns$chr
> [1] 1  2  3  4  5  6  7  8  9  10 11 12 13 14 15 16 17 18 19 20 21 22
> Levels: 1 10 11 12 13 14 15 16 17 18 19 2 20 21 22 3 4 5 6 7 8 9
>
> but when I run this : plot(new_ns$chr,new_ns$nc_two)
>
> the order of new_ns$chr is 1 10 11 12 13 14 15 16 17 18 19 2 20 21 22
> 3 4 5 6 7 8 9
> how can fix this order to 1  2  3  4  5  6  7  8  9  10 11 12 13 14 15
> 16 17 18 19 20 21 22 in the plot ?

 > new_ns$chr <- factor(as.character(new_ns$chr))
 > new_ns$chr
# I needed to apply as.character to a numeric vector  before factor()  
to get this ordering.
# Otherwise it  with the expected order.

  [1] 1  2  3  4  5  6  7  8  9  10 11 12 13 14 15 16 17 18 19 20 21 22
Levels: 1 10 11 12 13 14 15 16 17 18 19 2 20 21 22 3 4 5 6 7 8 9

 > levels(new_ns$chr) <- 1:22
 > new_ns$chr
  [1] 1  12 16 17 18 19 20 21 22 2  3  4  5  6  7  8  9  10 11 13 14 15
Levels: 1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22


> I attached the plot.

Correction: you probably tried to attach the plot. If so, it was  
scrubbed by the mail server because you did not follow the directions  
in the Posting Guide.

David Winsemius, MD
West Hartford, CT



More information about the R-help mailing list