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 ?
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
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)
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With