0

I am using R.
I have a two sets of columns in my data frame (DT): R1, R2,...,R6 and U1, U2,...U6. R1 and U1 are related, R2 and U2 are related and so on.
When I sort (R1,...,R6), I also need to the same order values for (U1,...,U6) i.e. when I have:

R1 R2 R3 R4 R5 R6 U1 U2 U3 U4 U5 U6
2 3 1 8 4 5 .1 .5 .9 .1 .2 .5
1 5 9 2 6 3 .1 .2 .3 .4 .5 .6
I want to transform this to:
R1 R2 R3 R4 R5 R6 U1 U2 U3 U4 U5 U6
8 5 4 3 2 1 .1 .5 .2 .5 .1 .9
9 6 5 3 2 1 .3 .5 .2 .6 .4 .1

This is what I am doing, but its taking very long since DT has 100,000 records. Columns 1:6 are R1:R6 and am storing the sorted values of U1 through U6 in OU1:OU6

# This piece of code sorts R1 through R6
DT=cbind(DT, t(apply(-DT[,1:6] 1, sort)))
 DT[,13:18]=-1*S_RU[,13:18]
#This piece of code sorts U1 through U6
for(i in 1:nrow(DT)){
 x=as.numeric(DT[i,c("U1","U2","U3","U4","U5","U6")] ) 
 S_RU[i,c("OU6","OU5","OU4","OU3","OU2","OU1")]=x[order(-S_RU[i,1:6])]
 }
asked Jun 20, 2017 at 3:53

1 Answer 1

1

How about:

#example data
DT <- as.data.frame(matrix(c(2,3,1,8,4,5,.1,.5,.9,.1,.2,.5,1,5,9,2,6,3,.1,.2,.3,.4,.5,.6), byrow = T, ncol = 12))
colnames(DT) <- c(paste0("R",1:6),paste0("U",1:6))
DT
# do as you like
mtx <- apply(DT, 1, function(x) {
 R <- order(x[1:6], decreasing = T)
 c(x[1:6][R], x[7:12][R])
 })
# returning the correct formatting and names in one go
setNames(as.data.frame(t(mtx)), colnames(DT))
# R1 R2 R3 R4 R5 R6 U1 U2 U3 U4 U5 U6
#1 8 5 4 3 2 1 0.1 0.5 0.2 0.5 0.1 0.9
#2 9 6 5 3 2 1 0.3 0.5 0.2 0.6 0.4 0.1
answered Jun 20, 2017 at 4:22
0

Your Answer

Draft saved
Draft discarded

Sign up or log in

Sign up using Google
Sign up using Email and Password

Post as a guest

Required, but never shown

Post as a guest

Required, but never shown

By clicking "Post Your Answer", you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.