Yamuna_dhungana
Yamuna_dhungana

Reputation: 663

How to reorder dataframe by column values given by a target vector

I have a matrix like this:

structure(c("A1", "B", "C", "A1", "A2", "C", "1", "2", "3", "4", 
"5", "6"), .Dim = c(6L, 2L))

I want to use the target vector

target <- c("A1","A2", "B", "C")

to reorder the rows and get a dataframe like this:

"A1" "1" 
"A1" "4"
"A2" "5"
"B"  "2" 
"C"  "3" 
"C"  "6" 

Upvotes: 1

Views: 50

Answers (1)

akrun
akrun

Reputation: 887088

We can use order on the match between the first column of the dataset and the 'target' vector

df1[order(match(df1[,1], target)),]

-output

#     [,1] [,2]
#[1,] "A1" "1" 
#[2,] "A1" "4" 
#[3,] "A2" "5" 
#[4,] "B"  "2" 
#[5,] "C"  "3" 
#[6,] "C"  "6" 

Or another option is to set the levels of the first column as 'target' and order

df1[order(factor(df1[,1], levels = target)),]

Upvotes: 1

Related Questions