2017-06-20 98 views
0

我正在使用R
我在我的数据帧(DT)中有两组列: R1,R2,...,R6和U1,U2,... U6。 R1和U1是相关的,R2和U2是相关的,等等。
当我排序(R1,...,R6),我还需要为(U1,...,U6),即以相同的顺序值时,我有:

如何根据R数据框中的另一组列对列的一组进行排序

R1 R2 R3 R4 R5 R6 U1 U2 U3 U4 U5 U6
0.1   0.5   0.9   0.1   0.2   0.5
0.1   0.2   0.3   0.4   0.5   0.6
欲将此变换:
R1 R2 R3 R4 R5 R6 U1 U2 U3 U4 U5 U6
0.1   0.5   0.2   0.5   0.1   0.9
0.3   0.5   0.2   0.6   0.4   0.1

这是我在做什么,但它采取非常长,因为DT有10万条记录。 列1:6 R1:R6和我通过U6在OU1存储U1的排序值: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])] 
    } 

回答

1

如何:

#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 
+0

非常感谢埃文。这工作超快 – Tecsanto

+0

当然,我的荣幸。 –

相关问题