2
votes

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.

2
Please read some introduction to R. This is really basic stuff.Roland
can you please precise your question. Do you want to order columns or order according to columns? What is the expected result?agstudy
@Fuv8 Please show representative input and intended output.Roland
How do you expect ties to be handled?BenBarnes
no preference BenBarnes. Just produce a list of data.frames sorted according to each element of DF2 each time if I understand correctly your question.Fuv8

2 Answers

2
votes

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
0
votes

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