Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

how to arrange odd numbers in descending and even even numbers in ascending order in dplyr

Tags:

r

I have following dataframe in r

   ID     bay    row     number     
   1      43      11       ABC
   2      43      6        DEF
   3      43      13       QWE
   4      43      15       XDF
   5      43      4        VGH
   6      43      2        TYU
   7      11      11       QAS
   8      11      13       QTO
   9      11      12       EWQ
   10     11      10       RFT  

I want to arrange odd numbers in descending and even even numbers in ascending order grouping by bay

My desired dataframe would be following

  ID     bay     row     number     
  1       43      15      XDF
  2       43      13      QWE
  3       43      11      ABC
  4       43      2       TYU
  5       43      4       VGH
  6       43      6       DEF
  7       11      13      QTO 
  8       11      11      QAS
  9       11      10      RFT 
 10       11      12      EWQ   

How can I do this in dplyr ?

like image 233
Neil Avatar asked Sep 15 '25 19:09

Neil


2 Answers

library(dplyr)

df <- read.table(text =
"   ID     bay    row     number     
   1      43      11       ABC
   2      43      6        DEF
   3      43      13       QWE
   4      43      15       XDF
   5      43      4        VGH
   6      43      2        TYU
   7      11      11       QAS
   8      11      13       QTO
   9      11      12       EWQ
   10     11      10       RFT ",
  stringsAsFactors = FALSE, header = TRUE)

arrange(df, desc(bay), desc(row %% 2), row * (-1)^(row%%2))

#    ID bay row number
# 1   4  43  15    XDF
# 2   3  43  13    QWE
# 3   1  43  11    ABC
# 4   6  43   2    TYU
# 5   5  43   4    VGH
# 6   2  43   6    DEF
# 7   8  11  13    QTO
# 8   7  11  11    QAS
# 9  10  11  10    RFT
# 10  9  11  12    EWQ
like image 63
Aurèle Avatar answered Sep 18 '25 10:09

Aurèle


For a base solution, split the data by whether row is odd or even, and use mapply to sort them separately.

df <- 
  structure(list(ID = 1:10, 
                 bay = c(43L, 43L, 43L, 43L, 43L, 43L, 
                         11L, 11L, 11L, 11L), 
                 row = c(11L, 6L, 13L, 15L, 4L, 2L, 11L, 
                         13L, 12L, 10L), 
                 number = c("ABC", "DEF", "QWE",
                            "XDF", "VGH", "TYU", 
                            "QAS", "QTO", "EWQ", 
                            "RFT")), 
            .Names = c("ID", "bay", "row", "number"), 
            class = "data.frame", 
            row.names = c(NA, -10L))

df <- split(df, df$row %%2 == 0)

df <- 
  mapply(function(DF, decr) DF[order(DF$row, decreasing = decr), ],
         df,
         decr = c(TRUE, FALSE),
         SIMPLIFY = FALSE)

df <- do.call("rbind", df)
like image 34
Benjamin Avatar answered Sep 18 '25 09:09

Benjamin