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
Post a Comment