Xiaokang
Xiaokang

Reputation: 331

Is there an elegant way to reorder data frame by rownames in R

I have a dataframe with random row names. And I would like to reorder it by the row names. Say the original dataframe looks like:

       value
gene8  0.140533602
gene6 21.129493396
gene7  0.170091711
gene3 28.101415822
gene1  0.005706749
gene2  3.157911375

And what I want is:

       value
gene1  0.005706749
gene2  3.157911375
gene3 28.101415822
gene6 21.129493396
gene7  0.170091711
gene8  0.140533602

After searching for the solution, I've found two ways that can almost solve the issue:

  1. Using function arrange(). But it can't take row name as the sorting index.
  2. Using function order() and do it in this way df <- df[order(row.names(df)), ]. But what you get is a numeric vector instead of a dataframe. So the row name will be missing.

Solution 1 looks very elegant, but it can't achieve my goal. Solution 2 can be used, but some extra work needs to be added (creating a new dataframe assigning the values and row names). Is there a straight-forway way to do the job?

Upvotes: 2

Views: 1400

Answers (3)

GKi
GKi

Reputation: 39667

Add drop = FALSE to disable coercion to the lowest possible dimension.

df <- df[order(row.names(df)), , drop = FALSE]

Upvotes: 3

shs
shs

Reputation: 3901

Works just fine with arrange():

library(dplyr)

d <- read.table(textConnection("
             value
gene8  0.140533602
gene6 21.129493396
gene7  0.170091711
gene3 28.101415822
gene1  0.005706749
gene2  3.157911375")) 


d %>% 
  arrange(row.names(.))
#>              value
#> gene1  0.005706749
#> gene2  3.157911375
#> gene3 28.101415822
#> gene6 21.129493396
#> gene7  0.170091711
#> gene8  0.140533602

Upvotes: 1

Samet S&#246;kel
Samet S&#246;kel

Reputation: 2670

since there is one column subsetting returns a numeric vector, this will work;

df$dummycol <- rep(1,nrow(df))

df <- df[sort(rownames(df)),]

df$dummycol <- NULL

df

output;

        value
        <dbl>
gene1   0.005706749
gene2   3.157911375
gene3   28.101415822
gene6   21.129493396
gene7   0.170091711
gene8   0.140533602

Upvotes: 0

Related Questions