2017-04-07 50 views
0

我有来自在线调查的数据,其中受访者经历了一系列5个问题。 我在工作中的数据是这样的:收集专栏组

P1 P2 P3 P4 P5 P1 P2 P3 P4 P5 P1 P2 P3 P4 P5 
    1 2 3 4 5 1 2 3 4 5 1 2 3 4 5 
    6 7 8 9 10 6 7 8 9 10 6 7 8 9 10 

所需的输出是:

 P1 P2 P3 P4 P5 
    1 2 3 4 5 
    6 7 8 9 10 
    1 2 3 4 5 
    6 7 8 9 10 
    1 2 3 4 5 
    6 7 8 9 10 

我一直在试图解决这一问题库tidyr,但我不知道如何应用它。 一些建议,这将是非常有益的。

+1

你能'dput'你的数据对我们?你只是想将每一组5列叠加在一起? – A5C1D2H2I1M1N2O1R2T1

+0

检查http://stackoverflow.com/questions/15803057/binding-columns-with-similar-column-names-in-the-same-dataframe-in-r – timfaber

+0

我想这也适用:'data.frame(split (unlist(indf,use.names = FALSE),rep(names(indf),each = nrow(indf))))...... .... – A5C1D2H2I1M1N2O1R2T1

回答

0

一种解决方案可以是:

require(foreach) 
require(dplyr) 
require(magrittr)  

foreach(
    unique_name = unique(colnames(df)), 
    .combine = 'bind_cols' 
) %do% { 

    df[grep(unique_name), colnames(df)] %>% 
    unlist() %>% 
    as.data.frame() %>% 
    set_colnames(., unique_names) 

} 
+0

代码中有一个额外的''''' – manotheshark