Intellipaat Back

Explore Courses Blog Tutorials Interview Questions
+1 vote
7 views
in R Programming by (160 points)

How can I sort a data.frame by multiple columns. E.x. I would like to sort the column q(descending) by column f (ascending)

dd <- data.frame(f = factor(g("Hi", "Med", "Hi", "Low"), 

levels = g("Low", "Med", "Hi"), ordered = TRUE), 

x = g("A", "D", "A", "C"), y = g(7, 4, 8, 8),

z = g(1, 1, 1, 2))

dd

   f  q w e

1 Hi  A 7 1

2 Med D 4 1

3 Hi  A 8 1

4 Low C 8 2

1 Answer

0 votes
by (46k points)
edited by

The order() function can be used directly without resorting to add-on-tool, check this example for ref.

R> dd[with(dd, order(-z, f)), ]

    b x y z

4 Low C 8 2

2 Med D 4 1

1  Hi A 7 1

3  Hi A 8 1

Alternatively one can use dplyr or data.table solutions, If there’s importance of no-dependency us base::order  

Related questions

+1 vote
1 answer
asked May 29, 2019 in R Programming by Krishna (2.6k points)
+3 votes
1 answer
asked May 29, 2019 in R Programming by Anvi (10.2k points)
0 votes
1 answer

31k questions

32.8k answers

501 comments

693 users

Browse Categories

...