In R, sort a date frame by one column and by groups

3

I want to sort a date 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
    
asked by anonymous 26.04.2015 / 22:11

2 answers

3

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

I highly recommend learning the dplyr package for manipulating data in a dataframe.

Just enter the dataframe and columns in order of sorting

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 something in descending order, for example v2, use desc (nameColumn):

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
    
29.04.2015 / 03:30
2

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

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
    
27.04.2015 / 03:02