-2

i have below data format. it have cbind a,b data according to date.

a           b            days
--------------------------------
c(1,2,3)  c(1,2,3)   2018-06-22
c(4,5,6)  c(4,5,6)   2018-06-23
....
--------------------------------

and i wanna convert it to different formats that have a,b columns according to days

2018-06-22       2018-06-23   ....
-------------------------------
a      b         a        b
-----------------------------
1     1          4        4
2     2          5        5
3     3          3        3

how can i convert it ?

jerry han
  • 425
  • 4
  • 15
  • 1
    Related / possible duplicate: [*Split comma-separated strings in a column into separate rows*](https://stackoverflow.com/q/13773770/2204410) – Jaap Jun 25 '18 at 07:32
  • 2
    You might want to rethink your desired data structure. It is better to keep everything in long format. See above link for several solutions. – Jaap Jun 25 '18 at 07:33

1 Answers1

1

This is the best I can do. It uses data.table package and outputs your transformed data in long format.

require(data.table)

# your data
dt1 <- data.table(a = list(c(1,2,3),c(4,5,6)), b = list(c(1,2,3),c(4,5,6)), days =  c("2018-06-22","2018-06-23"))

# to long format
dt2 <- melt(dt1,id.vars = 3)

# unlist
dt3 <- dt2[ , unlist(value), by = c("days","variable")]

#result
  days variable V1
 1: 2018-06-22        a  1
 2: 2018-06-22        a  2
 3: 2018-06-22        a  3
 4: 2018-06-23        a  4
 5: 2018-06-23        a  5
 6: 2018-06-23        a  6
 7: 2018-06-22        b  1
 8: 2018-06-22        b  2
 9: 2018-06-22        b  3
10: 2018-06-23        b  4
11: 2018-06-23        b  5
12: 2018-06-23        b  6
moooh
  • 459
  • 3
  • 10