user3664020
user3664020

Reputation: 3020

Re arrange data frame

I have a data frame like

 col1   col2   col3   col4
  a       0     t      .1
  b       0     t      .2
  a       1     f      .3
  b       1     f      .4

I need to re arrange it to this format

         a     b
0   t   .1    .2
1   f   .3    .4

I know this can be done using dcast function. But I am not able figure out how exactly?

Upvotes: 0

Views: 69

Answers (1)

A5C1D2H2I1M1N2O1R2T1
A5C1D2H2I1M1N2O1R2T1

Reputation: 193497

As you mentioned, this can be done with dcast from "reshape2":

library(reshape2)
dcast(mydf, col2 + col3 ~ col1, value.var = "col4")
#   col2 col3   a   b
# 1    0    t 0.1 0.2
# 2    1    f 0.3 0.4

It can also be done with reshape from base R:

> reshape(mydf, direction = "wide", idvar = c("col2", "col3"), timevar = "col1")
  col2 col3 col4.a col4.b
1    0    t    0.1    0.2
3    1    f    0.3    0.4

And with spread, from "tidyr":

> library(dplyr)
> library(tidyr)
> mydf %>% spread(col1, col4)
  col2 col3   a   b
1    0    t 0.1 0.2
2    1    f 0.3 0.4

Upvotes: 2

Related Questions