HernanLG
HernanLG

Reputation: 666

Order a binded data.frame by decreasing frequency in R

I know that ordering by frequency is pretty straightforward in R. Given a data.frame df and a column column1 with numerical values:

order(df$column1,decreasing=T)

My data.frame is the result of having used rbind() on smaller data.frames. Each of the original data.frame had a column called Trial with values ranging from 1 to nrow(GralData) although some numbers were missing (due to outlier removal). Another column is called TrialType and can have two possible character values: "Regular" or "Random"

What I want to do is create two data.frames out of GralData. One containing only Regular in TrialType, and one only containing Random. Moreover, I want the new.data.frame to be ordered decreasingly according to the values of Trial. This is what I am using:

GralData_Regular <- GralData[GralData$TrialType=="Regular" & order(GralData$Trial,decreasing=TRUE),]

But, instead this command is ordering the rows keeping in mind the data.frames from which the rows came from. So instead of having all data mixed, order only according to the criterion of the value of the Trial column, values are ordered first by data.frame and then by order of the value of Trial. So the Trial column would look something like:

 1,2,3,4,5,1,2,3,4,5,1,2,3,4,5,etc...

And I want it to be

1,1,1,2,2,2,3,3,3,4,4,4,5,5,5,etc...

I hope I made myself clear. This is quite a small problem and I am sure I must be missing something basic, but I googled this extensively and didn't find any reference to the problem. Any advice is much appreciated.

Upvotes: 2

Views: 1671

Answers (1)

juba
juba

Reputation: 49033

You must do it in two steps :

## Subset the original data frame    
GralData_Regular <- GralData[GralData$TrialType=="Regular",]
## Sort it
GralData_Regular <- GralData_Regular[order(GralData_Regular$Trial,decreasing=TRUE),]

The & operator is used to combine logical vectors. Here your first condition is a logical vector (GralData$TrialType=="Regular"), but your second one is numerical (order(GralData$Trial,decreasing=TRUE)).

Upvotes: 4

Related Questions