2017-06-20 37 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

當然,我的榮幸。 –

相關問題