I'm trying to reorder column in a dataframe, in a descending or ascending order, based on unique values of another column in the same dataframe within groups.
To demonstrate this below is given an example in which a dataframe has three columns. The goal is to group by the gr
column, and to order the a
column based on the unique value of the b
column. So for example if within the gr=1
the unique value of the column b
is T then I would like the column a
in ascending order, and if not in descending order. The example is below
# sample dataset
df <- data.frame(
a = c(1,3,2,4),
b = c(T,T,F,F),
gr = c(1,1,2,2)
)
# split dataset according to a grouping column
df <- df %>% split(df$gr)
# ordering function
f1 <- function(dt) {
if (unique(dt$b) == T) {
arrange(dt, a)
} else {
arrange(dt, -a)
}
}
The desired dataset should look like this:
# order within groups based on variable b
df %>% purrr::map_df(f1)
Can this be done without using lists or tidyr::nest
? Using a simple dplyr::group_by
and dplyr::arrange
it should be possible and is the best desired answer.
a
you can see it has been reordered. Originally it is c(1,3,2,4), and at the end it is c(1,3,4,2) – adldf %>% arrange(gr, a * if_else(b, 1, -1))
– d.b