Not as concise as ronak-shah's answer, but you can also use order .
# extract row names temp <- row.names(foo) # reset of vector temp[which(temp %in% sel)] <- temp[rev(which(temp %in% sel))] # reset order of data.frame foo[order(temp),] 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
As noted in the comments, this depends on the names of the lines following the lexicographic order. In cases where this is not true, we can use match .
# set up set.seed(1234) foo <- data.frame(ID=1:10, x=1:10) row.names(foo) <- sample(LETTERS[1:10]) sel <- c("D", "H")
Now outlet names
# initial data.frame foo ID x B 1 1 F 2 2 E 3 3 H 4 4 I 5 5 D 6 6 A 7 7 G 8 8 J 9 9 C 10 10 # grab row names temp <- row.names(foo) # reorder vector containing row names temp[which(temp %in% sel)] <- temp[rev(which(temp %in% sel))]
Using match along with order
foo[order(match(row.names(foo), temp)),] ID x B 1 1 F 2 2 E 3 3 D 6 6 I 5 5 H 4 4 A 7 7 G 8 8 J 9 9 C 10 10
lmo
source share