Fuv8
Fuv8

Reputation: 905

Order according to a list of colnames

I have a first data.frame that looks like this:

DF1

          a    d    c    b
Name1     1    1   -1   -1      
Name2    -1    2   -3    1     
Name3     1    2   -1    0   
Name4     9    0    1   -10    

and a second data.frame containing the column names of DF1. In other words it looks like:

DF2
a
d
c
b

I would like to order (in decreasing order) DF1 according to: first DF2== a, then according to DF2 ==c, then according to DF2 ==d and so on. In the real case the DF2 is composed by around 1000 elements as well as the columns of DF1 with which each element of DF2 will be matched. The desired output will be:

After sorting for DF2[1,]

[[1]]

          a    d    c    b
Name1     9    0   -1   -10      
Name2     1    1   -3    1     
Name3     1    2   -1    0   
Name4    -1    2   -3    1    

After sorting for DF2[2,]

[[2]]

          a    d    c    b
Name1    -1    2   -3    1     
Name2     1    2   -1    0     
Name3     1    1   -1   -1   
Name4     9    0    1  -10  

And so on.

Upvotes: 2

Views: 192

Answers (2)

Roland
Roland

Reputation: 132576

Edited after the question has been clarified:

DF1 <- read.table(text="a    d    c    b
Name1     1    1   -1   -1      
Name2    -1    2   -3    1     
Name3     1    2   -1    0   
Name4     9    0    1   -10 ", header=TRUE)

DF2 <- data.frame(cols=c("a", "c", "d", "b"))


lapply(as.list(DF2$cols), 
       function(x,df) df[order(df[,x], decreasing=TRUE),], 
       df=DF1)

# [[1]]
#        a d  c   b
# Name4  9 0  1 -10
# Name1  1 1 -1  -1
# Name3  1 2 -1   0
# Name2 -1 2 -3   1
# 
# [[2]]
#        a d  c   b
# Name4  9 0  1 -10
# Name1  1 1 -1  -1
# Name3  1 2 -1   0
# Name2 -1 2 -3   1
# 
# [[3]]
#        a d  c   b
# Name2 -1 2 -3   1
# Name3  1 2 -1   0
# Name1  1 1 -1  -1
# Name4  9 0  1 -10
# 
# [[4]]
#        a d  c   b
# Name2 -1 2 -3   1
# Name3  1 2 -1   0
# Name1  1 1 -1  -1
# Name4  9 0  1 -10

Upvotes: 2

agstudy
agstudy

Reputation: 121568

I think you look for this:

DF[Reduce(order,DF),]
       a d  c   b
Name2 -1 2 -3   1
Name1  1 1 -1  -1
Name3  1 2 -1   0
Name4  9 0  1 -10

Upvotes: 0

Related Questions