简体   繁体   中英

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

use function unlist to merge all into one row

df <- data.frame(v1 = c(0.0000,0.1111,0.2222), v2 = c(1.11111,1.22222,1.33333))
 print(df)
      v1      v2
1 0.0000 1.11111
2 0.1111 1.22222
3 0.2222 1.33333
> df <- unlist (df, use.names = F)
> print(df)
 0.00000 0.11110 0.22220 1.11111 1.22222 1.33333

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))))

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM