Tzac
Tzac

Reputation: 101

Advanced ordering of data.frame using multiple columns

#data as follows;
values <- c(1,1,1,0,1,1)
values2 <- c(0,1,0,1,0,1)
values3 <- c(0,0,0,0,0,1)

Data <- data.frame(name = names, value = values, value2 = values2, value3 = values3)
Data[order(Data[,4], Data[,3], Data[,2]),] # basic ordering of data in base R

Question 1.

Is there a way to call something like Data[order(Data[,4:2],),] thus ordering all columns the same as the above code. (I have around 100 binary columns which I would like to use to order a data.frame consisting of 1600 rows and around 1620 columns so my code would look something like this Data[order(Data[,21:1620],),])

Question 2.

What if I wanted to have 'co-occurrences' ordered in a different configuration, consider;

smallData[order(smallData[,4], smallData[,3], smallData[,2]),]

Results:

   name value value2 value3
1  paul     1      0      0
3  dave     1      0      0
5  john     1      0      0
4  will     0      1      0
2  mark     1      1      0
6 steph     1      1      1

Instead I would like

   name value value2 value3
1  paul      1      0      0
3  dave      1      0      0
5  john      1      0      0
2  mark      1      1      0
6 steph      1      1      1
4  will      0      1      0

Upvotes: 1

Views: 54

Answers (1)

alistaire
alistaire

Reputation: 43334

1) dplyr's version of base::order is arrange, which is a little more flexible in what it takes, especially the SE version:

library(dplyr)
arrange_(Data, .dots = names(Data)[4:1])
#   names values values2 values3
# 1  john      1       0       0
# 2  mark      1       0       0
# 3  paul      1       0       0
# 4  will      0       1       0
# 5  dave      1       1       0
# 6 steph      1       1       1

2) You can arrange like this by inverting which direction you sort values:

arrange(Data, desc(values), values2)
#   names values values2 values3
# 1  paul      1       0       0
# 2  john      1       0       0
# 3  mark      1       0       0
# 4  dave      1       1       0
# 5 steph      1       1       1
# 6  will      0       1       0

Upvotes: 3

Related Questions