Moving some rows of a data frame to the end based on a match vector
Try this:
x <- as.character(df$id) %in% matchlist
rbind(df[!x,], df[x,])
# id A B
# 2 match4 4 in
# 8 match9 H under
# 9 match8 j in
# 13 match4 19 beside
# 1 match1 6 in
# 3 match1 8 in
# 4 match2 3 out
# 5 match3 T over
# 6 match2 8 in
# 7 match1 H over
# 10 match2 3 out
# 11 match1 20 under
# 12 match3 2 out
Consider this short tidyverse
solution:
mydata %>%
arrange(id %in% match_list)
Here is a solution without grep:
matched <- mydata$id %in% matchlist
mydata2 <- rbind(mydata[!matched,], mydata[matched,])
You could of course order the matched rows before the rbind, then you would get exactly the same output as in your example.