4

I execute the following code:

df<-data.frame(word=c("play","win","offer","http"),frequency=c(321,355,123,564),type=c("nonspam","nonspam","spam","spam"))

df=arrange(df,desc(frequency),desc(type))

df=df[order(df[,2],df[,3]),]

and the result is:

   word frequency type
4 offer       123    spam
3  play       321    nonspam
2   win       355    nonspam
1  http       564    spam

but I want to sort the data frame with respect to frequency and type such as:

word frequency type
    1  http      564    spam
    4  offer     123    spam
    2  win       355    nonspam
    3  play      321    nonspam
van boeren
  • 169
  • 2
  • 2
  • 9

1 Answers1

8

To sort in ascending order:

Use dplyr like this:

library(dplyr)
df <- df %>% arrange(type, frequency, word)

Just arrange the variables in the order you would like to sort.

To sort in descending order:

Just use a negative sign in front of the variable you want to sort in reverse order. Like this.

df %>% arrange(-type, frequency, word)

Working with text...

If you want to try sorting text in reverse order using the method above, you may get an error. To arrange categorical variables, wrap the variable around desc(), as such:

df %>% arrange(desc(word))
Joel Alcedo
  • 192
  • 4