+1 vote
2 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 (46.1k 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

+3 votes
1 answer
asked May 29, 2019 in R Programming by Anvi (10.2k points)
+1 vote
1 answer
asked May 29, 2019 in R Programming by Krishna (2.6k points)
0 votes
1 answer
Welcome to Intellipaat Community. Get your technical queries answered by top developers !


Categories

...