Reputation: 331
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:
arrange()
. But it can't take row name as the sorting index.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
Reputation: 39667
Add drop = FALSE
to disable coercion to the lowest possible dimension.
df <- df[order(row.names(df)), , drop = FALSE]
Upvotes: 3
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
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