2016-08-04 56 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