How to Sort a Data Frame in R

How to order a data frame by one descending and one ascending column?

I used this code to produce your desired output. Is this what you were after?

rum <- read.table(textConnection("P1  P2  P3  T1  T2  T3  I1  I2
2 3 5 52 43 61 6 b
6 4 3 72 NA 59 1 a
1 5 6 55 48 60 6 f
2 4 4 65 64 58 2 b"), header = TRUE)
rum$I2 <- as.character(rum$I2)
rum[order(rum$I1, rev(rum$I2), decreasing = TRUE), ]

P1 P2 P3 T1 T2 T3 I1 I2
1 2 3 5 52 43 61 6 b
3 1 5 6 55 48 60 6 f
4 2 4 4 65 64 58 2 b
2 6 4 3 72 NA 59 1 a

How to sort data by column in descending order in R

You need to use dataframe name as prefix

chickens[order(chickens$feathers),]  

To change the order, the function has decreasing argument

chickens[order(chickens$feathers, decreasing = TRUE),]  

Sort a data frame in R largest to smallest from value in a column

Could you please try following and let me know if this helps you.

library(dplyr)
df[with(df, order(-Letter)), ] %>% select (Number)

Output will be as follows.

6      F
5 E
4 D
3 C
2 B
1 A
>

Data created by as follows:

df <- data.frame(
v1 = c('A','B','C','D','E','F'),
v2 = c(1,2,3,4,5,6),
v3 = c(11,12,12.5,11.5,11.75,13)
)
colnames(df)<-c("Number","Letter","Age")

How can I sort a dataframe by a predetermined order of factor levels in R?

We can specify the levels of the 'group' as category_order and that use that to `arrange

library(dplyr)
df1 <- df %>%
arrange(factor(group, levels = category_order))
df1
# group value
#1 tree 50
#2 house 2
#3 lake 1
#4 human 5

Or using fct_relevel

library(forcats)
df %>%
arrange(fct_relevel(group, category_order))

sort dataframe r by column values

Substituting "DF" as your data frame, you can use this line of code:

DF[order(DF$new), ]

If you just wanted to view the data frame sorted, you can use

View(DF)

And click the arrows on the column name, which automatically sorts the data frame by ascending/descending.

Sort (order) data frame rows by multiple columns

You can use the order() function directly without resorting to add-on tools -- see this simpler answer which uses a trick right from the top of the example(order) code:

R> dd[with(dd, order(-z, b)), ]
b x y z
4 Low C 9 2
2 Med D 3 1
1 Hi A 8 1
3 Hi A 9 1

Edit some 2+ years later: It was just asked how to do this by column index. The answer is to simply pass the desired sorting column(s) to the order() function:

R> dd[order(-dd[,4], dd[,1]), ]
b x y z
4 Low C 9 2
2 Med D 3 1
1 Hi A 8 1
3 Hi A 9 1
R>

rather than using the name of the column (and with() for easier/more direct access).

Sort a data frame based on another sorted column value in R

With dplyr you can use

df %>% 
arrange(desc(var2), var1)

and afterwards you create the column rank



EDIT

The following code is a bit cumbersome but it gets the job done. Basically it orders the rows in which var2 is equal or different from zero separately, then combines the two ordered dataframes together and finally creates the rank column.

Data

df <- data.frame(
var1 = c("c","a","f","b","z","d", "c","a", "e", "z", "ad", "gf", "kg", "ts", "mp"),
var2 = c(134, NA,345, 200, 556,NA, 345, 200, 150, 0, 25,10,0,150,0),
var3 = as.numeric(c(65,'',45,34,68,'',73,12,35,23,34,56,56,78,123))
)
df
# var1 var2 var3
# 1 c 134 65
# 2 a NA NA
# 3 f 345 45
# 4 b 200 34
# 5 z 556 68
# 6 d NA NA
# 7 c 345 73
# 8 a 200 12
# 9 e 150 35
# 10 z 0 23
# 11 ad 25 34
# 12 gf 10 56
# 13 kg 0 56
# 14 ts 150 78
# 15 mp 0 123

Code

df %>% 
# work on rows with var2 different from 0 or NA
filter(var2 != 0) %>%
arrange(desc(var2), desc(var3)) %>%
# merge with rows with var2 equal to 0 or NA
bind_rows(df %>% filter(var2 == 0 | is.na(var2)) %>% arrange(var1)) %>%
arrange(desc(var2)) %>%
# create the rank column only for the rows with var2 different from NA
mutate(
rank = seq_len(nrow(df)),
rank = ifelse(is.na(var2), NA, rank)
)

Output

#    var1 var2 var3 rank
# 1 z 556 68 1
# 2 c 345 73 2
# 3 f 345 45 3
# 4 b 200 34 4
# 5 a 200 12 5
# 6 ts 150 78 6
# 7 e 150 35 7
# 8 c 134 65 8
# 9 ad 25 34 9
# 10 gf 10 56 10
# 11 kg 0 56 11
# 12 mp 0 123 12
# 13 z 0 23 13
# 14 a NA NA NA
# 15 d NA NA NA

Sort dataframe by custom order

If you want to keep the column as character rather than factor, you can arrange based on a match to the order vector

rating_order <- c("AAA", "AA", "A", "BBB", "BB", "B")

df <-
data.frame(
Rating = c("A", "AA", "AAA", "B", "BB", "BBB"),
Value1 = c(1, 2, 3, 4, 5, 6),
Value2 = c(2, 3, 4, 5, 3, 2)
)

library(dplyr, warn.conflicts = FALSE)

df %>%
arrange(match(Rating, rating_order))
#> Rating Value1 Value2
#> 1 AAA 3 4
#> 2 AA 2 3
#> 3 A 1 2
#> 4 BBB 6 2
#> 5 BB 5 3
#> 6 B 4 5

Created on 2022-01-20 by the reprex package (v2.0.1)

How to sort within a row of a data frame with categorical variables?

This is definitely much easier with long data, so, at least in dplyr, one has to pivot_longer then pivot_wider back:

library(dplyr)
library(tidyr)

test %>%
pivot_longer(cols = everything(), names_to = c(".value","col"), names_pattern = "(ClaimType|Time)(.*)") %>%
mutate(group = cumsum(col == 1)) %>%
arrange(group, Time, .by_group = T) %>%
mutate(col = sequence(rle(group)$l)) %>%
pivot_wider(id_cols = group, names_from = col, values_from = c("ClaimType","Time"), names_sep = "") %>%
select(-group)

ClaimType1 ClaimType2 ClaimType3 ClaimType4 Time1 Time2 Time3 Time4
<chr> <chr> <chr> <chr> <dbl> <dbl> <dbl> <dbl>
1 Class Derivative Derivative Class 1 2 8 10
2 Class Derivative Derivative Class 3 4 5 9


Related Topics



Leave a reply



Submit