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
  • 26,789
  • 2
  • 15
  • 32
vicky
  • 375
  • 1
  • 3
  • 12

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,350
  • 3
  • 13
  • 23
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 
Bappa Das
  • 5,817
  • 3
  • 18
  • 40