Fiona
Fiona

Reputation: 477

Make specific column the header in r (reshape/transpose)

I am trying to do something quite simple but can't find anything online (and am finding it hard to know what to google).

An example of the dataset I have is as follows.

TimeDiff      Speed       Direction
   3            0              0
   2            0             10
  54            0             15 
  36            0             20

I want to reshape the dataframe to look like as follows.

              0      10      15     20
TimeDiff      3      2       54     36
Speed         0      0       0      0

So I basically want to make the direction column my header and timediff and speed my rows.

Thanks for any help provided.

Upvotes: 0

Views: 139

Answers (1)

Maurits Evers
Maurits Evers

Reputation: 50668

How about this?

setNames(data.frame(t(df)[-ncol(df), ]), as.character(df[, ncol(df)]))
#         0 10 15 20
#TimeDiff 3  2 54 36
#Speed    0  0  0  0

This produces a data.frame of int columns.

str(setNames(data.frame(t(df)[-ncol(df), ]), as.character(df[, ncol(df)])))
#'data.frame':  2 obs. of  4 variables:
# $ 0 : int  3 0
# $ 10: int  2 0
# $ 15: int  54 0
# $ 20: int  36 0

Upvotes: 1

Related Questions