简体   繁体   中英

How to sort one set of columns based on another set of columns in R data frame

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) ie 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])]
  }

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

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM