2017-06-20 14 views
0

私はRを使用しています。
私は自分のデータフレーム(DT)に2組の列を持っています: 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
.1   0.5   0.9   .1   .2   0.5
R1 R2 R3 R4 R5 R6 U1とU2 U3のU4のU5のU6
:私はこれを変換したい2   .1   .2   .3   0.4   0.5   0.6
.1   0.5   .2   0.5   .1   0.9
0.3   0.5   0.2   0.6   0.4   0.1

これは私がやっているものですが、そのはDT以来、非常に時間がかかります100,000レコードあります。 列1:R6とOU1にU6を通じてU1のソートされた値を格納しています:6はR1です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

もちろん、私の喜び。 –

関連する問題