简体   繁体   中英

How to reverse the order of values in one column in a dataframe grouped by another column?

Given the following toy data frame:

df <- data.frame(A = c("A", "A", "A", "B", "B", "C", "C", "C", "C", "C"),
                 B = c(1, 2, 3, 1, 2, 1, 2, 3, 4, 5))

This data frame consists of 2 columns of which both columns are sorted ascending.

The desired result is the same data frame, but with reversed values for column 'B' for each group specified by the values in column 'A':

> df
   A B
1  A 3
2  A 2
3  A 1
4  B 2
5  B 1
6  C 5
7  C 4
8  C 3
9  C 2
10 C 1 

In this case column 'B' is numeric, therefore the use of the order function with a minus sign in front of df$B works

df$B <- df$B[order(df$A, -df$B)]

More general use is with the function xtfrm in case column 'B' is not numeric in other similar cases:

df$B <- df$B[order(df$A, -xtfrm(df$B))]

A simple, tidy way:

df %>% arrange(A, desc(B))

output as

   A B
1  A 3
2  A 2
3  A 1
4  B 2
5  B 1
6  C 5
7  C 4
8  C 3
9  C 2
10 C 1

You can try ave if you are with base R:

df <- within(df,B <- ave(B,A,FUN = function(x) sort(x,decreasing = TRUE)))

which gives

> df
   A B
1  A 3
2  A 2
3  A 1
4  B 2
5  B 1
6  C 5
7  C 4
8  C 3
9  C 2
10 C 1

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM