How to order data frame rows according to vector with specific order using R?

0 votes

Is there any way available to ensure that a data frame's rows are ordered according to the required/target vector.

Consider the example below for reference?

data <- data.frame(alphabets = letters[1:4], value = c(rep(TRUE, 2), rep(FALSE, 2)))

data
#   alphabets value
# 1    a      TRUE
# 2    b      TRUE
# 3    c      FALSE
# 4    d      FALSE

target <- c("b", "c", "a", "d")

However, the method below seems to be a little bit complicated:

id <- sapply(target, function(x) {
    which(data$alphabets == x)
})
data <- data[id,]
rownames(data) <- NULL

data 
#   alphabets value
# 1    b      TRUE
# 2    c      FALSE
# 3    a      TRUE
# 4    d      FALSE
Apr 30, 2018 in Data Analytics by CodingByHeart77
• 3,680 points
61 views

1 answer to this question.

0 votes

You can try using match:

data <- data.frame(alphabets=letters[1:4], value=c(rep(TRUE, 2), rep(FALSE, 2)))
target <- c("b", "c", "a", "d")
data[match(target, data$alphabets),]

  alphabets value
2    b      TRUE
3    c      FALSE
1    a      TRUE
4    d      FALSE

NOTE: It will work as long as your target/required  vector contains exactly the same elements as data$alphabets, and neither contains any duplicate values

match finds the row numbers that matches target's elements, and then we return data in that order.

answered Apr 30, 2018 by darklord
• 6,140 points

Related Questions In Data Analytics

0 votes
1 answer

How can I append rows to an R data frame?

Consider a dataSet i.e cicar(present under library ...READ MORE

answered May 8, 2018 in Data Analytics by zombie
• 3,690 points
38 views
0 votes
1 answer

How to filter a data frame with dplyr and tidy evaluation in R?

Requires the use of map_df to run each model, ...READ MORE

answered May 16, 2018 in Data Analytics by DataKing99
• 8,100 points
75 views
0 votes
2 answers
0 votes
1 answer
0 votes
1 answer

Discarding duplicate rows from a data.frame - R

You can use distinct() function along with ...READ MORE

answered May 4, 2018 in Data Analytics by Bharani
• 4,550 points
35 views
0 votes
1 answer

How to convert a list of vectors with various length into a Data.Frame?

We can easily use this command as.data.frame(lapply(d1, "length< ...READ MORE

answered Apr 4, 2018 in Data Analytics by DeepCoder786
• 1,700 points
60 views
0 votes
2 answers

In data frame how to spilt strings into values?

You can do this using dplyr and ...READ MORE

answered Dec 4, 2018 in Data Analytics by Kalgi
• 39,330 points
45 views
0 votes
1 answer
0 votes
2 answers

How to remove rows with missing values (NAs) in a data frame?

Hi, The below code returns rows without ...READ MORE

answered 4 days ago in Data Analytics by anonymous
• 21,430 points
4,152 views
0 votes
2 answers

How to sort a data frame by columns in R?

You can use dplyr function arrange() like ...READ MORE

answered 3 days ago in Data Analytics by anonymous
• 21,430 points
97 views