2016-03-21 8 views
-1

参照テーブルを使用して、いくつかの重要なフィールド(他の列)を保持する行にいくつかの列からのデータの位置を変更するためにIm Training。R for loop to slooow

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 

私は最初のテーブル内の振幅からより多くの列を持っている。この単なる例:

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 

は、私はこのような最終的な結果を得ました。

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

ベースv = names = c( "Value")、times = c( "A"、 "B")):R: 'reshape(df、varying = c(" A "、" B ")、direction = ' – Zelazny7

答えて

3

meltからdata.tableまでを使用できます。それはループforと比較して速くなければなりません。

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