How to sort a data frame by columns in R

+1 vote

I am considering the below data frame as an example to sort the data frame by columns. I want to sort the column 'd' in a descending manner and column 'b' in an ascending order. 

data <- data.frame(b = factor(c("Hey", "Medium", "Hey", "Low"), 
      levels = c("Low", "Medium", "Hey"), ordered = TRUE),
      x = c("W", "Z", "W", "Y"), y = c(7, 4, 8, 8),
      d = c(2, 2, 2, 3))
data
    b    x y d
1  Hey   W 7 2
2 Medium Z 4 2
3  Hey   W 8 2
4 Low    Y 8 3
Apr 10, 2018 in Data Analytics by nirvana
• 3,130 points
1,809 views

2 answers to this question.

0 votes

You can just use the order function with the column index as follows:

data[ order(-data[,4], data[,1]), ]
    b    x y d
4 Low    Y 8 3
2 Medium Z 4 2
1  Hey   W 7 2
3  Hey   W 8 2
answered Apr 10, 2018 by Sahiti
• 6,370 points
0 votes

You can use dplyr function arrange() like below.

library(dplyr)
data = data %>% arrange(-d)
answered Aug 21, 2019 by anonymous
• 33,030 points

Related Questions In Data Analytics

0 votes
1 answer
0 votes
1 answer

How to convert a list to data frame in R?

Let's assume your list of lists is ...READ MORE

answered Apr 12, 2018 in Data Analytics by nirvana
• 3,130 points

edited Apr 12, 2018 by nirvana 22,102 views
+1 vote
2 answers

How can I drop columns by name in a data frame ?

We can Drop Columns by name in ...READ MORE

answered Apr 14, 2018 in Data Analytics by zombie
• 3,790 points
28,426 views
0 votes
1 answer

How to convert tables to a data frame in R ?

> trial.table.df <- as.data.frame(trial.table) //assuming that trial.table ...READ MORE

answered Apr 20, 2018 in Data Analytics by zombie
• 3,790 points
7,599 views
0 votes
1 answer
0 votes
1 answer
0 votes
1 answer

How to apply list to a function which give data frame as output

If you use  tidyverse, you can use ...READ MORE

answered Apr 11, 2018 in Data Analytics by Sahiti
• 6,370 points
791 views
0 votes
1 answer

How to remove certain character from a vector

We can use sub to remove the * by specifying fixed = ...READ MORE

answered Nov 14, 2018 in Data Analytics by Maverick
• 10,840 points
726 views
0 votes
2 answers

How to remove rows with missing values (NAs) in a data frame?

Hi, The below code returns rows without ...READ MORE

answered Aug 20, 2019 in Data Analytics by anonymous
• 33,030 points
14,761 views
+1 vote
2 answers

How to replace a value in a data frame based on a conditional 'If' statement?

It's easier to convert alpha to characters ...READ MORE

answered Jun 6, 2018 in Data Analytics by Sahiti
• 6,370 points
36,652 views
webinar REGISTER FOR FREE WEBINAR X
REGISTER NOW
webinar_success Thank you for registering Join Edureka Meetup community for 100+ Free Webinars each month JOIN MEETUP GROUP