How to sort paragraph numbers

I have a simple table with paragraph numbering:

> table <- data.frame(id=c(1,2,3,4,5,6,7,8,9), paragraph=c("1.1.1.1","1","2","1.1","100","1.2","10","1.1.1","1.1.2"))
> print(table)

id paragraph
1   1.1.1.1
2         1
3         2
4       1.1
5       100
6       1.2
7        10
8     1.1.1
9     1.1.2
10     1.10

I would like to sort it as follows:

id paragraph
2         1
4       1.1
8     1.1.1
1   1.1.1.1
9     1.1.2
6       1.2
10     1.10
3         2
7        10
5       100

The problem for me (I could possibly split them into “.” On data.frame and then apply multiple column orderings) is that I don’t know how many points there could be in the output - the amount may vary at times .

+6
source share
1 answer

Here is one of the options:

sp <- strsplit(as.character(table$paragraph), "\\.")
ro <- sapply(sp, function(x) sum(as.numeric(x) * 100^(max(lengths(sp)) + 0:(1 - length(x)))))
table[order(ro), ]
#    id paragraph
# 2   2         1
# 4   4       1.1
# 8   8     1.1.1
# 1   1   1.1.1.1
# 9   9     1.1.2
# 6   6       1.2
# 10 10      1.10
# 3   3         2
# 7   7        10
# 5   5       100

, , sp . , , , 100 ^ n ( n) 100 ^ (n-1) ( 100 , ), , ro .

+2

All Articles