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


given data.frame:

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

i reorder subset of rows, defined row names. however, swap row names of foo well. can do

sel <- c("d", "h") # rows reorder foo[sel,] <- foo[rev(sel),] sel.wh <- match(sel, rownames(foo)) rownames(foo)[sel.wh] <- rownames(foo)[rev(sel.wh)] 

but long , complicated. there simpler way?

we can replace sel values in rownames 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 

Comments

Popular posts from this blog

commonjs - How to write a typescript definition file for a node module that exports a function? -

openid - Okta: Failed to get authorization code through API call -

ios - Change Storyboard View using Seague -