-2

I'm looking to reshape my dataframe as follow from :

     Ech   pos    sm    nb
   <int> <chr> <dbl> <dbl>
 1     4    BD    10    80
 2     4    BG     5    80
 3     4    HD     1    80
 4     4    HG     2    80

to

     Ech    BD   BG   HD   HG  nb
 1     4    10    5    1   2   80

my data :

DF=structure(list(Ech = c(4L, 4L, 4L, 4L, 13L, 13L, 13L, 13L, 28L, 
28L, 28L, 28L, 37L, 37L, 37L, 37L, 40L, 40L, 40L, 40L), pos = c("BD", 
"BG", "HD", "HG", "BD", "BG", "HD", "HG", "BD", "BG", "HD", "HG", 
"BD", "BG", "HD", "HG", "BD", "BG", "HD", "HG"), sm = c(10, 5, 
1, 2, 2, 4, 2, 1, 3, 7, 1, 2, 6, 4, 2, 4, 11, 8, 1, 4), nb = c(80, 
80, 80, 80, 80, 80, 80, 80, 80, 80, 80, 80, 80, 80, 80, 80, 80, 
80, 80, 80)), .Names = c("Ech", "pos", "sm", "nb"), row.names = c(NA, 
-20L), vars = "Ech", drop = TRUE, class = c("grouped_df", "tbl_df", 
"tbl", "data.frame"))

What is the fastest way to do this ? thanks

ranell
  • 683
  • 13
  • 29

1 Answers1

1

tidyr::spread does this:

spread(DF, pos, sm)

Output:

    Ech    nb    BD    BG    HD    HG
* <int> <dbl> <dbl> <dbl> <dbl> <dbl>
1     4    80    10     5     1     2
2    13    80     2     4     2     1
3    28    80     3     7     1     2
4    37    80     6     4     2     4
5    40    80    11     8     1     4
Marius
  • 58,213
  • 16
  • 107
  • 105