Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to sort a data frame in R

I am new to R, and want to sort a data frame called "weights". Here are the details:

>str(weights)
'data.frame':   57 obs. of  1 variable:
 $ attr_importance: num  0.04963 0.09069 0.09819 0.00712 0.12543 ...

> names(weights)
  [1] "attr_importance"

> dim(weights)
  [1] 57  1

> head(weights)
        attr_importance
make        0.049630556
address     0.090686474
all         0.098185517
num3d       0.007122618
our         0.125433292
over        0.075182467

I want to sort by decreasing order of attr_importance BUT I want to preserve the corresponding row names also.

I tried:

> weights[order(-weights$attr_importance),]

but it gives me a "numeric" back.

I want a data frame back - which is sorted by attr_importance and has CORRESPONDING row names intact. How can I do this?

Thanks in advance.

like image 235
user721975 Avatar asked Aug 01 '11 04:08

user721975


People also ask

How do I sort a DataFrame in R?

To sort a data frame in R, use the order( ) function. By default, sorting is ASCENDING. Prepend the sorting variable by a minus sign to indicate DESCENDING order.

How do you sort a DataFrame?

To sort the DataFrame based on the values in a single column, you'll use . sort_values() . By default, this will return a new DataFrame sorted in ascending order. It does not modify the original DataFrame.

What does arrange () do in R?

The arrange() function lets you reorder the rows of a tibble. It takes a tibble, followed by the unquoted names of columns. For example, to sort in ascending order of the values of column x , then (where there is a tie in x ) by descending order of values of y , you would write the following.


2 Answers

Since your data.frame only has one column, you need to set drop=FALSE to prevent the dimensions from being dropped:

weights[order(-weights$attr_importance),,drop=FALSE]
#         attr_importance
# our         0.125433292
# all         0.098185517
# address     0.090686474
# over        0.075182467
# make        0.049630556
# num3d       0.007122618
like image 158
Joshua Ulrich Avatar answered Sep 23 '22 07:09

Joshua Ulrich


rankdata.txt

regno   name           total    maths   science social cat
1   SUKUMARAN   400 78  89  73  S
2   SHYAMALA    432 65  79  87  S
3   MANOJ       500 90  129 78  C
4   MILYPAULOSE 383 59  88  65  G
5   ANSAL       278 39  77  60  O
6   HAZEENA     273 45  55  56  O
7   MANJUSHA    374 50  99  52  C
8   BILBU       408 81  97  72  S
9   JOSEPHROBIN 374 57  85  68  G
10  SHINY       381 70  79  70  S
z <- data.frame(rankdata)

z[with(z, order(-total+ maths)),]  #order function  maths group selection
z
z[with(z, order(name)),]  # sort on name
z
like image 31
V G Menon Avatar answered Sep 25 '22 07:09

V G Menon