roger
roger

Reputation: 149

convert rows into columns R

I have a dataframe with 2 columns:

a<-c(1, 3, 4, 6, 8.7, 9, 10, 12, 19.3, 20)
b<-c(10, 30, 40, 60, 87, 90, 100, 120, 190, 200)
df<-data.frame(a=a, b=b)
> df
      a   b
1   1.0  10
2   3.0  30
3   4.0  40
4   6.0  60
5   8.7  87
6   9.0  90
7  10.0 100
8  12.0 120
9  19.3 190
10 20.0 200

Please, My goal is to have 1 single line of 10 columns of a and 10 columns of b

Expected Result

    a1 a2   ...   a10  b1 b2 ... b10
1   1.0 3.0 ...   20.0 10 30 ... 200

I tried t() but its not giving me the result I want

Upvotes: 1

Views: 74

Answers (2)

Carles
Carles

Reputation: 2829

unlist() will do the trick:

unlist(df)
   a1    a2    a3    a4    a5    a6    a7    a8    a9   a10    b1    b2    b3    b4    b5    b6 
  1.0   3.0   4.0   6.0   8.7   9.0  10.0  12.0  19.3  20.0  10.0  30.0  40.0  60.0  87.0  90.0 
   b7    b8    b9   b10 
100.0 120.0 190.0 200.0 

Upvotes: 1

jay.sf
jay.sf

Reputation: 72593

Try unlist or as.data.frame(t(unlist(.))), depends on what you need, a vector or a data frame.

unlist(df)
# a1    a2    a3    a4    a5    a6    a7    a8    a9   a10    b1    b2    b3    b4    b5    b6    b7    b8    b9   b10 
# 1.0   3.0   4.0   6.0   8.7   9.0  10.0  12.0  19.3  20.0  10.0  30.0  40.0  60.0  87.0  90.0 100.0 120.0 190.0 200.0 
as.data.frame(t(unlist(df)))
#   a1 a2 a3 a4  a5 a6 a7 a8   a9 a10 b1 b2 b3 b4 b5 b6  b7  b8  b9 b10
# 1  1  3  4  6 8.7  9 10 12 19.3  20 10 30 40 60 87 90 100 120 190 200

Upvotes: 1

Related Questions