0

I am working with two dataframes. I want to reorder the rows of one dataframe so that it is identical to the order of the rows in the second dataframe. I have one dataframe with counts and the other with metadata. I need the same order to generate vectors of metadata for statistical comparisons.

df1
         ColName1 ColName2 ColName3
RowName1        3        0        5
Rowname2        0        1        7
Rowname3        0        2        2
Rowname4        9        3        4

df2
         ColName1 ColName2
RowName3        A        Q
Rowname2        A        W
Rowname4        B        Q
Rowname1        B        W

I expect to get

 df2
             ColName1 ColName2
    RowName1        B        W
    Rowname2        A        W
    Rowname3        A        Q
    Rowname4        B        Q

I have seen post no. 27362718 and tried

df2[order(match(rownames(df2), rownames(df1))), ]

but it haven't worked.

match(rownames(df2), rownames(df1))

lists order indicating which rows does not match.

order(match(rownames(df2), rownames(df1)))

lists order but the rest does not set the order.

Can anyone help? Best regards, Marcin

mschmidt
  • 19
  • 5
  • 1
    Please show a small reproducible exampel with expected output. thanks – akrun Jan 26 '21 at 18:45
  • *"but it haven't worked"* - please be more specific. Did you get an error? A warning? A completely wrong result? A result that was mostly correct but had some issues? – Gregor Thomas Jan 26 '21 at 19:01
  • 1
    Though, the example you are following is using a column, not row names. Since you actually have row names, you can probably use `df2[rownames(df1), ]` – Gregor Thomas Jan 26 '21 at 19:02
  • I did not get any error message. The code was done but when I check if the order is the same with all(rownames(df1) == rownames(df2)) it returns FALSE. Both dataframes have the same number of rows – mschmidt Jan 26 '21 at 19:13
  • Thanks Gregor! the `df2[rownames(df1), ]` works fine! – mschmidt Jan 26 '21 at 19:39

0 Answers0