0

I want to re-shape my data frame in R. enter image description here

Here is a re-producible example:

ID <- c(1,1,1,2,2,2,3,3,3)
type <- c("date","value","volume","date","value","volume","date","value","volume")
value <- c("2020-01","100","1","2020-01","200","9","2020-02","100","3")
df <- data.frame(ID, type, value)

Thank you for your time.

IceCreamToucan
  • 28,083
  • 2
  • 22
  • 38
vicky
  • 395
  • 1
  • 3
  • 15

2 Answers2

1

That's a long to wide conversion

You can use reshape2::melt or tidyr::pivot_wider

ID <- c(1,1,1,2,2,2,3,3,3)
type <- c("date","value","volume","date","value","volume","date","value","volume")
value <- c("2020-01","100","1","2020-01","200","9","2020-02","100","3")
df <- data.frame(ID, type, value)

reshape2::dcast(df, ID ~...)
  ID    date value volume
1  1 2020-01   100      1
2  2 2020-01   200      9
3  3 2020-02   100      3
linog
  • 5,786
  • 3
  • 14
  • 28
1

tidyverse solution

library(tidyverse)
pivot_wider(df, id_cols = ID,names_from = type, values_from = value)

# A tibble: 3 x 4
     ID date    value volume
  <dbl> <fct>   <fct> <fct> 
1     1 2020-01 100   1     
2     2 2020-01 200   9     
3     3 2020-02 100   3 
UseR10085
  • 7,120
  • 3
  • 24
  • 54