How to sort a numerical factor column in an R data frame?

R ProgrammingServer Side ProgrammingProgramming

To sort a numerical factor column in an R data frame, we would need to column with as.character then as.numeric function and then order function will be used.

For Example, if we have a data frame called df that contains a numerical factor column say F then we can use sort F by using the below mentioned command −

df[order(as.numeric(as.character(df$F))),]

Example 1

Following snippet creates a sample data frame −

Class<-factor(sample(1:4,20,replace=TRUE))
Sales<-sample(1:50,20)
df1<-data.frame(Class,Sales)
df1

The following dataframe is created

  Class Sales
 1 1    4
 2 2   13
 3 3    2
 4 2   39
 5 2   23
 6 3   37
 7 4   33
 8 3   16
 9 4   17
10 2   20
11 3   50
12 1   27
13 4    6
14 4   19
15 4   48
16 3   43
17 4   31
18 3   35
19 2   14
20 4   45

To sort Class column of df1 on the above created data frame, add the following code to the above snippet −

Class<-factor(sample(1:4,20,replace=TRUE))
Sales<-sample(1:50,20)
df1<-data.frame(Class,Sales)
df1[order(as.numeric(as.character(df1$Class))),]

Output

If you execute all the above given snippets as a single program, it generates the following Output −

  Class Sales
 1 1     4
12 1    27
 2 2    13
 4 2    39
 5 2    23
10 2    20
19 2    14
 3 3     2
 6 3    37
 8 3    16
11 3    50
16 3    43
18 3    35
 7 4    33
 9 4    17
13 4     6
14 4    19
15 4    48
17 4    31
20 4    45

Example 2

Following snippet creates a sample data frame −

Group<-factor(sample(1:3,20,replace=TRUE))
Demand<-sample(500:1000,20)
df2<-data.frame(Group,Demand)
df2

The following dataframe is created

  Group Demand
 1 1    625
 2 3    855
 3 3    809
 4 2    951
 5 2    939
 6 2    629
 7 2    902
 8 1    903
 9 3    633
10 1    886
11 1    962
12 2    577
13 1    660
14 3    709
15 1    584
16 3    889
17 1    762
18 3    594
19 2    779
20 2    859

To sort Group column of df2 on the above created data frame, add the following code to the above snippet −

Group<-factor(sample(1:3,20,replace=TRUE))
Demand<-sample(500:1000,20)
df2<-data.frame(Group,Demand)
df2[order(as.numeric(as.character(df2$Group))),]

Output

If you execute all the above given snippets as a single program, it generates the following Output −

  Group Demand
 1 1    625
 8 1    903
10 1    886
11 1    962
13 1    660
15 1    584
17 1    762
 4 2    951
 5 2    939
 6 2    629
 7 2    902
12 2    577
19 2    779
20 2    859
 2 3    855
 3 3    809
 9 3    633
14 3    709
16 3    889
18 3    594
raja
Published on 10-Nov-2021 06:17:24
Advertisements