user53020
user53020

Reputation: 889

R sort data based on first digit

I am trying to sort out the data based on the first digit of numbers. For e.g.

#Generate sample data
dat<-round(runif(5,90,99),digits=0)
dat1<-round(runif(5,1515,1590),digits=0)
dat2<-round(runif(5,156,190),digits=0)
dat3<-round(runif(5,900,999),digits=0)

data<-c(dat,dat1,dat2,dat3)

If I want to sort the data, I do this

sort(data)

However, what I want to do is to sort the data according to the first digit. For example, all numbers starting with 9 should appear first and all the numbers starting with 1 should appear later. something like this

90,93,96,97,98,938,944,953,973,983,168,169,177,183,188,1515,1560,1563,1564,1587

Is there anyway I can do this in R?

Thanks

Upvotes: 0

Views: 1212

Answers (1)

akrun
akrun

Reputation: 887213

We can use substr to extract the first digit and order the 'data' based on that.

data[order(-as.numeric(substr(data, 1, 1)), data)]
#[1]   90   93   96   97   98  938  944  953  973  983  168  169  177  183  188 1515 1560 1563 1564 1587

data

data <- c(938, 1515, 90, 1587, 188, 983, 1560, 973, 183, 168, 1563, 98,  
         96, 177, 169, 97, 953, 944, 93, 1564)

Upvotes: 1

Related Questions