Home > other >  How to organize a data frame's columns, according to another data frame's rows?
How to organize a data frame's columns, according to another data frame's rows?

Time:11-02

I have two data frames, here is only a little fraction of the first (named mydata2):

enter image description here

and my second data frame (named scores) :

enter image description here

I want the order of the columns in the second one to be as the order of the rows in the first one.

CodePudding user response:

dat1 <- data.frame(a=1:3)
rownames(dat1) <- c("AA","BB","CC")
dat1
#    a
# AA 1
# BB 2
# CC 3
dat2 <- data.frame(ZZ=11:12, BB=21:22, CC=31:32, AA=41:42)
dat2
#   ZZ BB CC AA
# 1 11 21 31 41
# 2 12 22 32 42

We'll use match to match the column names with the row names:

ind <- match(colnames(dat2), rownames(dat1))
ind
# [1] NA  2  3  1

If you want non-matches (if present) at the beginning, then

dat2[, order(!is.na(ind), ind)]
#   ZZ AA BB CC
# 1 11 41 21 31
# 2 12 42 22 32

Else

dat2[, order(is.na(ind), ind)]
#   AA BB CC ZZ
# 1 41 21 31 11
# 2 42 22 32 12
  • Related