0

In my dataset, there are values from 1.1 to 1.12

R, by default, order them showing 1.10, 1.11 and 1.12 before 1.2.

Example:

## V1  V2
## A   1.1 
## B   1.10
## J   1.11
## K   1.12
## G   1.2
## D   1.3
## E   1.4
## J   1.5
## G   1.6
## T   1.7
## R   1.8
## O   1.9

How can I change the order of V2 ordering the values from 1.1 to 1.12?

(In this way)

## V1  V2
## A   1.1 
## G   1.2
## D   1.3
## E   1.4
## J   1.5
## G   1.6
## T   1.7
## R   1.8
## O   1.9
## B   1.10
## J   1.11
## K   1.12

of course my real dataset is more complex but i belive that a solution for this case could solve my problem

Thanks!

2 Answers2

2

If the column V2 is of class "character", the following code using function str_order of package stringr will order the data.frame by numeric order of V2.

i <- stringr::str_order(df1$V2, numeric = TRUE)
df1 <- df1[i, ]

df1
#   V1   V2
#1   A  1.1
#5   E  1.2
#6   F  1.3
#7   G  1.4
#8   H  1.5
#9   I  1.6
#10  J  1.7
#11  K  1.8
#12  L  1.9
#2   B 1.10
#3   C 1.11
#4   D 1.12

I have left the row names unordered to show that the entire rows have changed their position, not just column V2. To reset the row names,

row.names(df1) <- NULL

Test data

V1 <- LETTERS[1:12]
V2 <- sprintf("1.%d", 1:12)
V2 <- sort(V2)
df1 <- data.frame(V1, V2)
Rui Barradas
  • 70,273
  • 8
  • 34
  • 66
0

Here's a tidyverse solution:

library(tidyverse)

data <- data.frame(V1 = LETTERS[seq(1, 20)], V2 = paste0(1, ".", seq(1,20)))
data_sorted <- data %>%
      separate(V2, sep = "\\.", into = c("left", "right"), remove = F) %>%
      arrange(left, right) %>%
      select(-left, -right)

data_sorted
#>    V1   V2
#> 1   A  1.1
#> 2   J 1.10
#> 3   K 1.11
#> 4   L 1.12
#> 5   M 1.13
#> 6   N 1.14
#> 7   O 1.15
#> 8   P 1.16
#> 9   Q 1.17
#> 10  R 1.18
#> 11  S 1.19
#> 12  B  1.2
#> 13  T 1.20
#> 14  C  1.3
#> 15  D  1.4
#> 16  E  1.5
#> 17  F  1.6
#> 18  G  1.7
#> 19  H  1.8
#> 20  I  1.9

Created on 2021-01-08 by the reprex package (v0.3.0)

Mario Niepel
  • 1,095
  • 4
  • 19