How to sort a data frame by columns in R?

0 votes

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,060 points
119 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 darklord
• 6,140 points
0 votes

You can use dplyr function arrange() like below.

library(dplyr)
data = data %>% arrange(-d)
answered Aug 21 by anonymous
• 25,660 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,060 points

edited Apr 12, 2018 by nirvana 2,501 views
0 votes
1 answer

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

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

answered Apr 13, 2018 in Data Analytics by zombie
• 3,690 points
36 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,690 points
55 views
0 votes
1 answer
0 votes
1 answer
0 votes
1 answer
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,040 points
43 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 in Data Analytics by anonymous
• 25,660 points
4,459 views
0 votes
1 answer

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 darklord
• 6,140 points
46 views