2016-03-21 81 views
-1

使用參考表,我正在搜索重新定位從幾列到保留一些重要字段(其他列)的行的數據。R for循環到sloow

Name Amplitude A   B   
M2  3.264   29.0  28.98 
S2  0.781   51.9  30.0 
N2  0.63   12.3  28.43 
K1  1.263  136.8  15.04 
M4  0.043  286.0  57.96 

我有一個最後的結果是這樣的:

Name Amplitude Value Code   
M2  3.264   29.0 A  
S2  0.781   51.9 A  
N2  0.63   12.3 A  
K1  1.263  136.8 A  
M4  0.043  286.0 B 
M2  3.264  28.98 B 
S2  0.781   30.0 B 
N2  0.63   15.04 B 
K1  1.263  57.96 B 

這只是一個例子,我有從振幅在第一個表更多的列到一個。我使用下面的代碼:

Final<-NULL 

colname<-colnames(ReferenceAll) 

for (i in (1:nrow(ReferenceAll))){ 
    for (j in (1:ncol(ReferenceAll))){ 
    if (j>2) { # the number is from the column I want to get in the results 

    temp<-as.data.frame(rbind(cbind(Name=ReferenceAll[i,1], 
            Amplitude=as.character.factor(ReferenceAll[i,2]), 
            Value=ReferenceAll[i,j], 
            Code=colname[j]))) 
    Final<-rbind(Final,temp)}}} 

當我有幾行需要毫秒,但是當我有超過100行需要時間。誰能幫我?

+2

'庫(reshape2);熔體(DF1,id.vars = C( 「姓名」, 「振幅」),value.name = 「值」,variable.name = 「代碼」)' – RHertel

+1

基R:'reshape(df,vary = c(「A」,「B」),direction =「long」,v.names = c(「Value」),times = c(「A」,「B」)) ' – Zelazny7

回答

3

我們可以從data.table使用melt。與for循環相比,它應該很快。

library(data.table) 
melt(setDT(df1), id.var=1:2, value.name="Value", variable.name="Code")