Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Reorder a subset of an R data.frame modifying the row names as well

Tags:

dataframe

r

Given a data.frame:

foo <- data.frame(ID=1:10, x=1:10)
rownames(foo) <- LETTERS[1:10]

I would like to reorder a subset of rows, defined by their row names. However, I would like to swap the row names of foo as well. I can do

sel <- c("D", "H") # rows to reorder
foo[sel,] <- foo[rev(sel),]
sel.wh <- match(sel, rownames(foo))
rownames(foo)[sel.wh] <- rownames(foo)[rev(sel.wh)]

but that is long and complicated. Is there a simpler way?

like image 469
January Avatar asked Apr 06 '17 10:04

January


People also ask

How do I reorder Dataframe rows 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.

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.

Can you subset rows in R?

Subsetting in R is a useful indexing feature for accessing object elements. It can be used to select and filter variables and observations. You can use brackets to select rows and columns from your dataframe.


1 Answers

We can replace the sel values in rownames with the reverse of sel.

x <- rownames(foo)
foo[replace(x, x %in% sel, rev(sel)), ]

#  ID  x
#A  1  1
#B  2  2
#C  3  3
#H  8  8
#E  5  5
#F  6  6
#G  7  7
#D  4  4
#I  9  9
#J 10 10
like image 126
Ronak Shah Avatar answered Oct 13 '22 01:10

Ronak Shah