In R, sort a data frame by column and by groups

Asked

Viewed 1,739 times

3

I want to sort a data frame according to a v2 column and respecting the groups column. For example, suppose I have df as follows

df
v1 v2 grupo
1   5   1
4   1   1
1   2   1
5   7   2
4   2   2
1   9   2

I want the result to be

df
v1 v2 grupo
4   1   1
1   2   1
1   5   1
4   2   2
5   7   2
1   9   2

2 answers

4


You can also use the function arrange package dplyr, which particularly I find easier both in reading and writing than the "normal way".

I highly recommend learning the dplyr package for data manipulation on a dataframe.

Just inform the dataframe and columns in order of ordering

v1 <- c(1,4,1,5,4,1)
v2 <- c(5,1,2,7,2,9)
grupo <- c(1,1,1,2,2,2)
df <- data.frame(v1,v2,grupo)

library(dplyr)

arrange(df, grupo, v2)
# v1 v2 grupo
# 4  1     1
# 1  2     1
# 1  5     1
# 4  2     2
# 5  7     2
# 1  9     2

If you want one in descending order, for example v2, use desc(nomeColune):

arrange(df, grupo, desc(v2))
# v1 v2 grupo
# 1  5     1
# 1  2     1
# 4  1     1
# 1  9     2
# 5  7     2
# 4  2     2

2

You can use order() with more than one condition, placing the columns in priority order:

df <- read.table(text="v1 v2 grupo
                 1   5   1
                 4   1   1
                 1   2   1
                 5   7   2
                 4   2   2
                 1   9   2", header=TRUE)

df[order(df$grupo, df$v2),]    
#   v1 v2 grupo
# 2  4  1     1
# 3  1  2     1
# 1  1  5     1
# 5  4  2     2
# 4  5  7     2
# 6  1  9     2

Browser other questions tagged

You are not signed in. Login or sign up in order to post.