Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
177 views
in Technique[技术] by (71.8m points)

Reordering rows in a dataframe according to the order of rows in another dataframe using rownames in R

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

question from:https://stackoverflow.com/questions/65907382/reordering-rows-in-a-dataframe-according-to-the-order-of-rows-in-another-datafra

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Answer

0 votes
by (71.8m points)
Waitting for answers

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...