Replace the R subset of the data file by changing the row names

Given data.frame:

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

I would like to reorder the subset of strings defined by their string names. However, I would like to change the line names of foo. 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 it is a long and complicated process. Is there an easier way?

+8
r order dataframe
source share
3 answers

We can replace the sel values ​​in rownames with the back 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 
+6
source share

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 
+2
source share

your data frame is small, so you can duplicate it, and then change the value of each raw:

 footmp<-data.frame(foo) foo[4,]<-footemp[8,] foot{8,]<-footemp[4,] 

Bean

0
source share