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 the order of attr_importance, but I also want to keep the corresponding row names.

I tried:

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

but it returns me a numeric number.

I want the data frame to be returned - which is sorted by attr_importance and has CORRESPONDING line names. How can i do this?

Thanks in advance.

+6
source share
3 answers

Since your data.frame has only one column, you need to set drop=FALSE to prevent deleting sizes:

 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 
+8
source

Here is a great comparison of sorting data.frame:

How to sort data by columns (columns)?

Using my now preferred arrange solution:

 dd <- data.frame(b = factor(c("Hi", "Med", "Hi", "Low"), levels = c("Low", "Med", "Hi"), ordered = TRUE), x = c("A", "D", "A", "C"), y = c(8, 3, 9, 9), z = c(1, 1, 1, 2)) library(plyr) arrange(dd,desc(z),b) bxyz 1 Low C 9 2 2 Med D 3 1 3 Hi A 8 1 4 Hi A 9 1 
+9
source

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 
0
source

Source: https://habr.com/ru/post/894006/


All Articles