Jack Armstrong
Jack Armstrong

Reputation: 1249

Sort a data frame in R largest to smallest from value in a column

Very simple concept. I have a dataframe, df and would like to sort it from largest to smallest value from a column and then get the first two columns in a new table. But I run into a small issue it seems.

df<-df[-order(df$col2),]

but the error I get is that object of type 'closure' is not subsettable.

In theory once I get the data sorted I was going to use cbind to pull out the two columns I needed and put into a new dataframe. That much I can do.

Sample:

v2<-c(1,2,3,4,5,6)
v1<-c('A','B','C','D','E','F')
v3<-c(11,12,12.5,11.5,11.75,13)
df<-cbind(v1,v2,v3)
colnames(df)<-c("Number","Letter","Age")

Output:

df
  6  F
  5  E
  4  D
  3  C
  2  B
  1  A

Upvotes: 1

Views: 40241

Answers (2)

RavinderSingh13
RavinderSingh13

Reputation: 133528

Could you please try following and let me know if this helps you.

library(dplyr)
df[with(df, order(-Letter)), ] %>% select (Number)

Output will be as follows.

6      F
5      E
4      D
3      C
2      B
1      A
> 

Data created by as follows:

df <- data.frame(
  v1 = c('A','B','C','D','E','F'),
  v2 = c(1,2,3,4,5,6),
  v3 = c(11,12,12.5,11.5,11.75,13)
)
colnames(df)<-c("Number","Letter","Age")

Upvotes: 2

melatonin
melatonin

Reputation: 67

You can use the arrange function in dplyr to sort a column (or multiple if you'd like).

library(dplyr)

df <- data.frame(
       "Letter" = c('A','B','C','D','E','F'),
       "Number" = c(1,2,3,4,5,6),
       "Age" = c(11,12,12.5,11.5,11.75,13)
)


new_df <- df %>% 
 # desc orders from largest to smallest
 arrange(desc(Number)) %>%
 # select subsets the columns you want
 select(Letter, Number)

new_df

Letter Number   
1      F      6 
2      E      5 
3      D      4 
4      C      3 
5      B      2 
6      A      1 

Upvotes: 4

Related Questions