2016-03-21 82 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")