Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Order dataframe by column of another dataframe

Tags:

r

Consider the following df: df1 <-data.frame('GID'=c('GID1','GID3','GID2','GID1','GID2'), 'Sequence'= c(4,7,6,2,3)) df2 <- data.frame('GID' = c('GID3','GID1','GID2','GID1','GID2'),'Trial'=c('SA1','SA5','ES4','ES3','ES9'))

I want to order df1 by the column df2$GID such that I could cbind the df2$Trial column into df1. I know match can do that but match only finds the first occurrence of values and I have repeated values. Thus I'm confused on the way to do that as this is a subset of a large data.frame.

like image 298
moth Avatar asked Oct 20 '25 15:10

moth


1 Answers

Have you tried using match this way: df1 <- df1[match(df2$GID, df1$GID),] (make sure to review the results)?

 GID Sequence
2   GID3        7
1   GID1        4
3   GID2        6
1.1 GID1        4
3.1 GID2        6

Do you want to get the cartesian product of GID, Sequence and Trial?

Also, could there be any GID of df2 that is not present in df1 and how would you like to handle that?

Do you have any data acting as a "key", identifying uniquely each entry?

like image 115
LostIT Avatar answered Oct 23 '25 06:10

LostIT



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!