Search code examples
rmergeplyr

Merge rows of multiple columns into one (row) R


I have a data like this and would like to merge them into one row. Certainly I can do a for loop, but this is not elegant and in efficient. My current data:

0.063456491   0.004457746    0.013450942     0.023948062     0.02247313
0.003147881  -0.018681539   -0.009495686    -0.008677241     0.013863377
0.083954841   0.100283809    0.061790913    -0.004592628    -0.052269582
-0.021375194  -0.041536406  -0.044538945     0.023639958     0.037451282

Expected output:

0.063456491 0.004457746 0.013450942 0.023948062 0.02247313  0.003147881 -0.018681539    -0.009495686    -0.008677241    0.013863377 0.083954841 0.100283809 …

Many thanks, Phuong


Solution

  • If all your data is numeric and you want to extract it row-wise you could do

    data.frame(t(as.numeric(t(df))))
    
    #          X1          X2         X3         X4         X5          X6 ......
    #1 0.06345649 0.004457746 0.01345094 0.02394806 0.02247313 0.003147881 ......
    

    Or a more general as.vector approach would also work

    data.frame(t(as.vector(t(df))))