2016-08-04 27 views
1

我有數據幀df如下:分割數據幀然後合併垂直

df$x1 df$x2  df$x3 df$x4  df$x5 df$x6   
Acti  Acti  Arthrex Arthrex Aflac Aflac  
    4   5  3   1  2   5 
    1   3  5   2  1   4   

祝通過文本中第一行到分割數據幀,然後垂直合併。我期望的輸出將如下所示:

df$x1 df$x2   
Acti  Acti   
    4   5  
    1   3  
Arthrex Arthrex 
    3   1 
    5   2 
Aflac Aflac 
    2   5 
    1   4 

非常感謝您的幫助。

回答

2

下面是使用dplyr(假設你的數據被稱爲DF)的解決方案:

library(dplyr) 

t(df) %>% # transpose the data so that the first row is now the first col 
    as_data_frame() %>% # convert back to data.frame from matrix 
    group_by(V1) %>% # group the data by the first column 
    do(as_data_frame(t(.))) # transpose each group back to the correct orientation 

dplyr::do讓你對每個組進行任意操作,那麼行的結果結合到一起成爲一個data.frame。

+0

您的代碼產生錯誤。它產生'錯誤:is.list(x)不是TRUE'。 – Santosh

+0

我使用'as.data.frame'而不是'as_data_frame',它的工作完美。 – Santosh