Sorting a factor column in R dataframe according to another factor column

Viewed 52

I have a dataframe in R as given below

jj <- c("an","al","ak","cj","bd","bi","bj","bn","bl")
jk <- as.factor(c( 1,1,1,0,0,0,2,2,2))
jn <- as.factor(c(2,0,1,1,0,0,3,1,1))
df <- data.frame(jj,jk,jn)

df
  jj jk jn
1 an  1  2
2 al  1  0
3 ak  1  1
4 cj  0  1
5 bd  0  0
6 bi  0  0
7 bj  2  3
8 bn  2  1
9 bl  2  1

I want to sort it in a way as given below,

 jj jk jn
1 an  0  0
2 al  0  1
3 ak  0  2
4 cj  1  0
5 bd  1  0
6 bi  1  1
7 bj  2  1
8 bn  2  1
9 bl  2  3

I tried the code given below to sort the dataframe


> with(df, df[order(jk, jj, jn),])
  jj jk jn
5 bd  0  0
6 bi  0  0
4 cj  0  1
3 ak  1  1
2 al  1  0
1 an  1  2
7 bj  2  3
9 bl  2  1
8 bn  2  1

The above code sorts the dataframe according to the second column but I am not getting how to sort the third column in a way as shown above like the third column should be sorted according to each level of levels(df$jk).

2 Answers

Based on the comments and your expected output, try this. It is not entirely clear this is what you wanted.

library(dplyr)

df %>% 
  mutate(jk = sort(jk)) %>% 
  group_by(jk) %>% 
  mutate(jn = sort(jn))
# Groups:   jk [3]
  jj    jk    jn   
  <fct> <fct> <fct>
1 an    0     0    
2 al    0     1    
3 ak    0     2    
4 cj    1     0    
5 bd    1     0    
6 bi    1     1    
7 bj    2     1    
8 bn    2     1    
9 bl    2     3   

base R

df$jk_1 <- sort(df$jk)
df$jn_1 <- ave(df$jn, df$jk, FUN = sort)

  jj jk jn jk_1 jn_1
1 an  1  2    0    0
2 al  1  0    0    1
3 ak  1  1    0    2
4 cj  0  1    1    0
5 bd  0  0    1    0
6 bi  0  0    1    1
7 bj  2  3    2    1
8 bn  2  1    2    1
9 bl  2  1    2    3
Related